您好,欢迎访问一九零五行业门户网

Python内置bin函数详细介绍

英文文档:
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函数详细介绍的详细内容。
其它类似信息

推荐信息