类型错误:int() 参数必须是字符串或数字,而不是“二进制" [英] TypeError: int() argument must be a string or a number, not 'Binary'
问题描述
我正在处理 http://blog.thedigitalcatonline.com/blog/2015/05/13/python-oop-tdd-example-part1/#.VxEEfjE2sdQ.我正在迭代地解决这个问题.此时我有以下 Binary 类:
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
我正在使用 pytest 运行一套测试,包括:
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
推荐答案
int
函数无法处理用户定义的类,除非您在类中指定它应该如何工作.__int__
(不是 init)函数为内置的 Python int()
函数提供有关如何将用户定义的类(在本例中为 Binary)转换为内部
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
我还建议对 __init__
函数的输入和 self.value
的值进行标准化.目前,它可以接受字符串(例如 '0b011'
或 0x3
)或 int.为什么不总是让它接受一个字符串作为输入,并且总是将 self.value 保持为一个 int.
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.
这篇关于类型错误:int() 参数必须是字符串或数字,而不是“二进制"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!