首页 > 编程语言 > 详细

python内置函数1-bin()

时间:2017-02-14 22:53:46      阅读:273      评论:0      收藏:0      [点我收藏+]

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,这是表示二进制的意思


如果对象不是整数,则报错

>>> class A:

...     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__方法,但返回值不是整数,报错

>>> class B:

...     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的类型

>>> class myType:

...     def __index__(self):

...         return 35

... 

>>> myvar=myType()

>>> bin(myvar)

‘0b100011‘


本文出自 “大云技术” 博客,请务必保留此出处http://hdlptz.blog.51cto.com/12553181/1897559

python内置函数1-bin()

原文:http://hdlptz.blog.51cto.com/12553181/1897559

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!