Python內置函數(5)——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'
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,775評論 0 33
  • The Python Data Model If you learned another object-orien...
    plutoese閱讀 1,782評論 0 51
  • 折騰了那么久,終于塵埃落定。 以為如釋重負,實則暗潮洶涌。 所有的苦與樂,自己慢慢消化。
    容玲閱讀 302評論 0 1
  • 感賞兒子最近著涼生病了,自己主動要求要吃藥。 感賞兒子在我一次次的發瘋過后,還選擇繼續愛我。 感賞婆婆為我留晚飯。...
    許曉凌_中閱讀 184評論 0 0
  • 聽說世界上每天會產出2000多部電影,但是大部分人一生連2000部電影這個數量也沒有看夠。歸根結底,除了時間原因,...
    莊曉魚閱讀 1,083評論 3 3