【发布时间】:2016-04-16 15:53:36
【问题描述】:
我正在处理这个tutorial。我正在迭代地解决这个问题。此时我有以下二进制类:
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=16)
else:
print(self.value)
return int(self.value)
我正在使用 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'
我问了一个关于这个TypeError: int() argument must be a string or a number, not 'Binary' 的问题,并根据答案将代码更改为如上。现在,当我使用 pytest 运行测试套件时,所有测试都失败了,错误是:
TypeError: __init__() should return None, not 'int'
为什么会出现问题?
【问题讨论】:
-
该答案不会从
__init__返回int。它定义了一个__int__方法,用于数值转换。 -
__init__()用于初始化对象,所以不要那样使用它,而是为以后的目的使用单独的方法。 -
为什么这是一个类而不仅仅是一个函数?