[英]TypeError: int() argument must be a string or a number, not 'Binary'
I'm working through http://blog.thedigitalcatonline.com/blog/2015/05/13/python-oop-tdd-example-part1/#.VxEEfjE2sdQ . 我正在通过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: 我正在使用pytest进行一系列测试,包括:
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
The int
function cannot deal with user defined classes unless you specify in the class how it should work. 除非您在类中指定它应该如何工作,否则
int
函数不能处理用户定义的类。 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. __int__
(不是init)函数提供了内置的python int()
函数信息,该信息与如何将用户定义的类(在这种情况下为Binary)转换为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
. 我可能还会建议标准化
__init__
函数的输入和self.value
的值。 Currently, it can accept either a string (eg '0b011'
or a 0x3
) or an int. 当前,它可以接受字符串(例如
'0b011'
或0x3
)或整数。 Why not just always make it accept a string as input and always keep self.value as an int. 为什么不总是让它接受一个字符串作为输入,而总是将self.value保留为一个整数呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.