Home  >  Article  >  Backend Development  >  Detailed introduction to Python’s built-in bin function

Detailed introduction to Python’s built-in bin function

高洛峰
高洛峰Original
2017-03-21 11:33:402719browse

English documentation:

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.

Instructions:

1. Convert an integer number into a binary string

>>> b = bin(3) 
>>> b
'0b11'
>>> type(b) #获取b的类型
<class &#39;str&#39;>

2. If the parameter x is not an integer, then x must define an __index__() method, and the method return value must be an integer.

2.1 If the object is not an integer, an error will be reported

>>> class A:
    pass

>>> a = A()
>>> bin(a) 
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    bin(a)
TypeError: &#39;A&#39; object cannot be interpreted as an integer

2.2 If the object defines the __index__ method, but the return value is not an integer, an error will be reported

>>> 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 The object defines _ _index__ method, and the return value is an integer, convert the __index__ method return value into a binary string

>>> class C:
    def __index__(self):
        return 3

>>> c = C()
>>> bin(c)
&#39;0b11&#39;

The above is the detailed content of Detailed introduction to Python’s built-in bin function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn