Home >Backend Development >Python Tutorial >Detailed introduction to Python's built-in bin function
English documentation:
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.
Instructions:
1. Convert an integer number into a binary string
>>> b = bin(3) >>> b '0b11' >>> type(b) #获取b的类型 <class 'str'>
2. If the parameter x is not an integer, then x must define an __index__() method, and the method return value must be an integer.
2.1 If the object is not an integer, an error will be reported
>>> 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 If the object defines the __index__ method, but the return value is not an integer, an error will be reported
>>> 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 The object defines _ _index__ method, and the return value is an integer, convert the __index__ method return value into a binary string
>>> class C: def __index__(self): return 3 >>> c = C() >>> bin(c) '0b11'
The above is the detailed content of Detailed introduction to Python's built-in bin function. For more information, please follow other related articles on the PHP Chinese website!