Python built-in functions (5) -- bin, python built-in function bin
English document:
bin
(X)
Convert an integer number to a binary string. The result is a valid Python expression. IfXIs not a Pythonint
Object, it has to define__index__()
Method that returns an integer.
Note:
1. convert an integer to a binary string
>>> B = bin (3) >>> B '0b11 '>>> type (B) # obtain the type of B <class 'str'>
2. If the x parameter is not an integer, x must define a _ index _ () method, and the return value of the method must be an integer.
2.1 if the object is not an integer, an error is returned.
>>> 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 _ index _ method is defined but the return value is not an integer, an error is returned.
>>> 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 the _ index _ method and the return value is an integer. Convert the return value of the _ index _ method to a binary string.
>>> class C: def __index__(self): return 3>>> c = C()>>> bin(c)'0b11'