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

Python内置函数bin()

作者: 简书冷雨 | 来源:发表于2017-09-14 17:27 被阅读0次

    bin(x)

    返回前缀为“0b”的二进制字符串.

    说明

    如果参数 x 是整数,函数返回 x 对应的前缀为“0b”的二进制字符串;

    如果 x 不是 int 对象,则 x 对象必须包含方法 __index__(),并且方法 __index__() 的返回值必须是一个整数。

    示例

    >>> bin(25)
    '0b11001'
    >>> bin(-25)
    '-0b11001'
    
    >>> # 非整型的情况
    ... class fooType:
    ...     pass
    ...
    >>> t=fooType()
    >>> bin(t)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'fooType' object cannot be interpreted as an integer
    >>> 
    >>> 
    >>> class fooType:
    ...     def __index__(self):
    ...             return 25
    ... 
    >>> t=fooType()
    >>> bin(t)
    '0b11001'
    
    

    相关文章

      网友评论

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

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