🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Python `bin()`函数 > 原文: [https://thepythonguru.com/python-builtin-functions/bin/](https://thepythonguru.com/python-builtin-functions/bin/) * * * 于 2020 年 1 月 7 日更新 * * * `bin()`函数以字符串形式返回整数的二进制表示形式。 其语法如下: ```py bin(number) -> binary representation ``` | 参数 | 描述 | | --- | --- | | `number` | 任何数值 | 这是一个例子: ```py >>> >>> bin(4) # convert decimal to binary '0b100' >>> >>> >>> bin(0xff) # convert hexadecimal to binary, 0xff is same decimal 255 '0b11111111' >>> >>> >>> bin(0o24) # convert octacl to binary, 0o24 is same decimal 20 '0b10100' >>> ``` ```py print(bin(4)) print(bin(0xff)) print(bin(0o24)) ``` ## `bin()`与用户定义的对象 * * * 要将`bin()`与用户定义的对象一起使用,我们必须首先重载`__index__()`方法。 在切片和索引的上下文中,`__index__()`方法用于将对象强制为整数。 例如,考虑以下内容: ```py >>> >>> l = [1, 2, 3, 4, 5] >>> >>> x, y = 1, 3 >>> >>> >>> l[x] 2 >>> >>> >>> l[y] 4 >>> >>> >>> l[x:y] [2, 3] >>> ``` ```py l = [1, 2, 3, 4, 5] x, y = 1, 3 print(l[x]) print(l[y]) print(l[x:y]) ``` 当我们使用索引和切片访问列表中的项目时,内部 Python 会调用`int`对象的`__index__()`方法。 ```py >>> >>> l[x.__index__()] # same as l[x] 2 >>> >>> >>> l[y.__index__()] # same as l[y] 4 >>> >>> >>> l[x.__index__():y.__index__()] # # same as l[x:y] [2, 3] >>> ``` ```py l = [1, 2, 3, 4, 5] x, y = 1, 3 print(l[x.__index__()]) print(l[y.__index__()]) print(l[x.__index__():y.__index__()]) ``` 除了`bin()`之外,在对象上调用`hex()`和`oct()`时也会调用`__index__()`方法。 这是一个例子: ```py >>> >>> class Num: ... def __index__(self): ... return 4 ... >>> >>> l = [1, 2, 3, 4, 5] >>> >>> >>> n1 = Num() >>> >>> >>> bin(n1) 0b100 >>> >>> >>> hex(n1) 0x4 >>> >>> >>> oct(n1) 0o4 >>> >>> >>> l[n1] 5 >>> >>> >>> l[n1.__index__()] 5 >>> ``` ```py class Num: def __index__(self): return 4 l = [1, 2, 3, 4, 5] n1 = Num() print(bin(n1)) print(hex(n1)) print(oct(n1)) print(l[n1]) print(l[n1.__index__()]) ``` * * * * * *