Python built-in functions (5) -- bin, python built-in function bin

Source: Internet
Author: User

Python built-in functions (5) -- bin, python built-in function bin

English document:

bin(X)

Convert an integer number to a binary string. The result is a valid Python expression. IfXIs not a PythonintObject, it has to define__index__()Method that returns an integer.

Note:

1. convert an integer to a binary string

>>> B = bin (3) >>> B '0b11 '>>> type (B) # obtain the type of B <class 'str'>

2. If the x parameter is not an integer, x must define a _ index _ () method, and the return value of the method must be an integer.

2.1 if the object is not an integer, an error is returned.

>>> 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 If the _ index _ method is defined but the return value is not an integer, an error is returned.

>>> 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 the _ index _ method and the return value is an integer. Convert the return value of the _ index _ method to a binary string.

>>> class C:    def __index__(self):        return 3>>> c = C()>>> bin(c)'0b11'

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.