登录  /  注册
Python内置bin函数详细介绍
高洛峰
发布: 2017-03-21 11:33:40
原创
2213人浏览过

英文文档:

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 'str'>
登录后复制

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: 'A' 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)
'0b11'
登录后复制

以上就是Python内置bin函数详细介绍的详细内容,更多请关注php中文网其它相关文章!

相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学