Python內建bin函數詳細介紹

來源:互聯網
上載者:User
英文文檔:

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'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.