英文文檔: 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 ...
英文文檔:
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'