首页 > 后端开发 > Python教程 > Python内置bin函数详细介绍

Python内置bin函数详细介绍

高洛峰
发布: 2017-03-21 11:33:40
原创
2769 人浏览过

英文文档:

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.

说明:

    1. 将一个整形数字转换成二进制字符串

>>> b = bin(3) 
>>> b
'0b11'
>>> type(b) #获取b的类型
<class &#39;str&#39;>
登录后复制

2. 如果参数x不是一个整数,则x必须定义一个 __index__() 方法,并且方法返回值必须是整数。

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

>>> class A:
    pass

>>> a = A()
>>> bin(a) 
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    bin(a)
TypeError: &#39;A&#39; object cannot be interpreted as an integer
登录后复制

2.2 如果对象定义了__index__方法,但返回值不是整数,报错

>>> class B:
    def __index__(self):
        return "3"

>>> b = B()
>>> bin(b)
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    bin(b)
TypeError: __index__ returned non-int (type str)
登录后复制

2.3 对象定义了__index__方法,且返回值是整数,将__index__方法返回值转换成二进制字符串

>>> class C:
    def __index__(self):
        return 3

>>> c = C()
>>> bin(c)
&#39;0b11&#39;
登录后复制

 

以上是Python内置bin函数详细介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
调用函数不用print(函数())格式??
来自于 1970-01-01 08:00:00
0
0
0
函数中的函数如何调用父函数的变量?
来自于 1970-01-01 08:00:00
0
0
0
函数函数函数
来自于 1970-01-01 08:00:00
0
0
0
“INET6_ATON” SQL 函数的 Python 等效项
来自于 1970-01-01 08:00:00
0
0
0
python同时执行两个函数
来自于 1970-01-01 08:00:00
0
0
0
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板