简体   繁体   English

TypeError:int()参数必须是字符串或数字,而不是'Binary'

[英]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.

相关问题 TypeError:int()参数必须是字符串或数字,而不是“列表” - TypeError: int() argument must be a string or a number, not 'list' TypeError:int()参数必须是字符串或数字,而不是&#39;tuple&#39; - TypeError: int() argument must be a string or a number, not 'tuple' 类型错误:INT()参数必须是字符串或数字,而不是“字典” - TypeError: int() argument must be a string or a number, not 'dict' Django-TypeError:int()参数必须是字符串或数字,而不是&#39;dict&#39; - Django - TypeError: int() argument must be a string or a number, not 'dict' TypeError:int()参数必须是字符串或数字,而不是&#39;Model Instance&#39;-Heroku - TypeError: int() argument must be a string or a number, not 'Model Instance' - Heroku TypeError:int()参数必须是字符串或数字,而不是使用ouchdb-python的“元组” - TypeError: int() argument must be a string or a number, not 'tuple' with couchdb-python TypeError:int()参数必须是字符串或数字,而不是“ Popen” Python - TypeError: int() argument must be a string or a number, not 'Popen' Python 类型错误:int() 参数必须是字符串、对象或数字,而不是“时间戳” - TypeError: int() argument must be a string, object or a number, not 'Timestamp' TypeError:int()参数必须是字符串或数字,而不是&#39;datetime.datetime&#39; - TypeError: int() argument must be a string or a number, not 'datetime.datetime' Python:TypeError:int()参数必须是字符串或数字,而不是“ IPv4Network” - Python: TypeError: int() argument must be a string or a number, not 'IPv4Network'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM