问题
I'm working through http://blog.thedigitalcatonline.com/blog/2015/05/13/python-oop-tdd-example-part1/#.VxEEfjE2sdQ . I'm working through this iteratively. At this point I have the following Binary class:
class Binary:
def __init__(self,value):
self.value = str(value)
if self.value[:2] == '0b':
print('a binary!')
self.value= int(self.value, base=2)
elif self.value[:2] == '0x':
print('a hex!')
self.value= int(self.value, base=5)
else:
print(self.value)
return None
I'm running through a suite of tests using pytest, including:
def test_binary_init_hex():
binary = Binary(0x6)
assert int(binary) == 6
E TypeError: int() argument must be a string or a number, not 'Binary'
def test_binary_init_binstr():
binary = Binary('0b110')
assert int(binary) == 6
E TypeError: int() argument must be a string or a number, not 'Binary'
I don't understand this error. What am I doing wrong?
edit: heres the class produced by the blog author:
import collections
class Binary:
def __init__(self, value=0):
if isinstance(value, collections.Sequence):
if len(value) > 2 and value[0:2] == '0b':
self._value = int(value, base=2)
elif len(value) > 2 and value[0:2] == '0x':
self._value = int(value, base=16)
else:
self._value = int(''.join([str(i) for i in value]), base=2)
else:
try:
self._value = int(value)
if self._value < 0:
raise ValueError("Binary cannot accept negative numbers. Use SizedBinary instead")
except ValueError:
raise ValueError("Cannot convert value {} to Binary".format(value))
def __int__(self):
return self._value
回答1:
The int function cannot deal with user defined classes unless you specify in the class how it should work. The __int__ (not init) function gives the built-in python int() function information regarding how your user defined class (in this case, Binary) should be converted to an int.
class Binary:
...your init here
def __int__(self):
return int(self.value) #assuming self.value is of type int
Then you should be able to do things like.
print int(Binary(0x3)) #should print 3
I might also suggest standardizing the input for the __init__ function and the value of self.value. Currently, it can accept either a string (e.g '0b011' or a 0x3) or an int. Why not just always make it accept a string as input and always keep self.value as an int.
来源:https://stackoverflow.com/questions/36652639/typeerror-int-argument-must-be-a-string-or-a-number-not-binary