美文网首页
Python内置函数(5)——bin

Python内置函数(5)——bin

作者: 十月狐狸 | 来源:发表于2016-12-29 11:55 被阅读0次

    英文文档:

    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'
    

    相关文章

      网友评论

          本文标题:Python内置函数(5)——bin

          本文链接:https://www.haomeiwen.com/subject/agnuvttx.html