# 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__()])
```
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象