英文文件:
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__()##__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 integer2.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中文網其他相關文章!