python内置方法补充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.

New in version 2.6.

中文说明:将整数x转换为二进制字符串,如果x不为Python中int类型,x必须包含方法__index__()并且返回值为integer;

参数x:整数或者包含__index__()方法切返回值为integer的类型;

版本:bin函数是python2.6中新增函数,使用时要注意版本问题。

实例讲解

1
2
3
4
5
6
7
8
9
10
11
12
13
#整数的情况
>>> bin(521)
#这里的显示结果形式与我们平时习惯有些差别,主要是前面多了0b,这是表示二进制的意思。
'0b1000001001'
#非整型的情况,必须包含__index__()方法切返回值为integer的类型
>>> class myType:
...   def __index__(self):
...     return 35
    
>>> myvar = myType()
>>> bin(myvar)
    
'0b1000001001'

PS:改函数非常简单,但是要注意版本,和参数类型。

原文地址:https://www.cnblogs.com/pyrene/p/6486149.html