Help on built-in function bin in module __builtin__:
bin(...)
bin(number) -> string
Return the binary representation of an integer or long integer.
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.
说明:将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer;
参数x:整数或者包含__index__()方法切返回值为integer的类型;
>>> bin(123)
'0b1111011'
>>> a=bin(67)
>>> a
'0b1000011'
这里的显示结果形式与我们平时习惯有些差别,主要是前面多了0b,这是表示二进制的意思
如果对象不是整数,则报错
>>>> ... pass
...
>>> a=A()
>>> bin(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object cannot be interpreted as an index
如果对象定义了__index__方法,但返回值不是整数,报错
>>>> ... def __index__(self):
... return "56"
...
>>> b=B()
>>> bin(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __index__ returned non-(int,long) (type str)
非整型的情况,必须包含__index__()方法切返回值为integer的类型