Python内置函数bin()

2017-09-14  本文已影响0人  简书冷雨

bin(x)

返回前缀为“0b”的二进制字符串.

说明

如果参数 x 是整数,函数返回 x 对应的前缀为“0b”的二进制字符串;

如果 x 不是 int 对象,则 x 对象必须包含方法 __index__(),并且方法 __index__() 的返回值必须是一个整数。

示例

>>> bin(25)
'0b11001'
>>> bin(-25)
'-0b11001'

>>> # 非整型的情况
... class fooType:
...     pass
...
>>> t=fooType()
>>> bin(t)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'fooType' object cannot be interpreted as an integer
>>> 
>>> 
>>> class fooType:
...     def __index__(self):
...             return 25
... 
>>> t=fooType()
>>> bin(t)
'0b11001'

上一篇下一篇

猜你喜欢

热点阅读