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'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM