TypeError: int() argument must be a string or a number, not 'Binary'

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。我正在迭代地解决这个问题。此时我有以下二进制 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 的一套测试,包括:

    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'

我不明白这个错误。我做错了什么?

编辑:这里是博客作者制作的class:

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 函数无法处理用户定义的 classes,除非您在 class 中指定它应该如何工作。 __int__(不是 init)函数提供了内置的 python int() 函数信息,说明您的用户如何定义 class(在本例中为二进制)应转换为整数

class Binary:
    ...your init here
    def __int__(self):
        return int(self.value) #assuming self.value is of type int

那么你应该可以做类似的事情。

print int(Binary(0x3)) #should print 3

我可能还建议标准化 __init__ 函数的输入和 self.value 的值。目前,它可以接受字符串(例如 '0b011'0x3)或整数。为什么不总是让它接受一个字符串作为输入并始终将 self.value 保持为 int.