英文文档
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
bin()
1、将一个整型数字转换成二进制字符串
>>> a = bin(1)
>>> a
'0b1'
>>> type(a) #获取a的类型
<class 'str'>
2、如果参数x不是一个整数,则x必须定义一个 __index__() 方法,并且方法返回值必须是整数。
下面来看一下详细代码说明:
#2.1 如果对象不是整数,则报错
>>> class A():
pass
>>> a = A()
>>> bin(a)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
bin(a)
TypeError: 'A' object cannot be interpreted as an integer
#2.2 如果对象定义了__index__方法,但返回值不是整数,报错
>>> class A():
def __index__(self):
return "1"
>>> b = A()
>>> bin(b)
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
bin(b)
TypeError: __index__ returned non-int (type str)
#2.3 对象定义了__index__方法,且返回值是整数,将__index__方法返回值转换成二进制字符串
>>> class A():
def __index__(self):
return 1
>>> c = A()
>>> bin(c)
'0b1'
小结
希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。
欢迎关注微信公众号,访问更多精彩:AiryData。
如需转载,请联系授权,谢谢合作。