# Python `*args`和`**kwargs`
> 原文: [https://thepythonguru.com/python-args-and-kwargs/](https://thepythonguru.com/python-args-and-kwargs/)
* * *
于 2020 年 1 月 7 日更新
* * *
什么是`*args`?
`*args`允許我們將可變數量的參數傳遞給函數。 讓我們以一個例子來闡明這一點。
假設您創建了一個將兩個數字相加的函數。
```py
def sum(a, b):
? ? print("sum is", a+b)
```
如您所見,該程序僅接受兩個數字,如果您要傳遞兩個以上的參數,這就是`*args`起作用的地方。
```py
def sum(*args):
? ? s = 0
? ? for i in args:
? ? ? ? s += i
? ? print("sum is", s)
```
現在,您可以像這樣將任意數量的參數傳遞給函數,
```py
>>> sum(1, 2, 3)
6
>>> sum(1, 2, 3, 4, 5, 7)
22
>>> sum(1, 2, 3, 4, 5, 7, 8, 9, 10)
49
>>> sum()
0
```
**注意**:
`*args`的名稱只是一個約定,您可以使用任何有效標識符。 例如`*myargs`是完全有效的。
## 什么是`**kwargs`?
* * *
`**kwargs`允許我們傳遞可變數量的關鍵字參數,例如`func_name(name='tim', team='school')`
```py
def my_func(**kwargs):
? ? for i, j in kwargs.items():
? ? ? ? print(i, j)
my_func(name='tim', sport='football', roll=19)
```
**預期輸出**:
```py
sport football
roll 19
name tim
```
## 在函數調用中使用`*args`和`**kwargs`
* * *
您可以使用`*args`將可迭代變量中的元素傳遞給函數。 以下示例將清除所有內容。
```py
def my_three(a, b, c):
? ? print(a, b, c)
a = [1,2,3]
my_three(*a) # here list is broken into three elements
```
**注意**:
僅當參數數量與可迭代變量中的元素數量相同時,此方法才有效。
同樣,您可以使用`**kwargs`來調用如下函數:
```py
def my_three(a, b, c):
? ? print(a, b, c)
a = {'a': "one", 'b': "two", 'c': "three" }
my_three(**a)
```
請注意,要使此工作有效,需要做兩件事:
1. 函數中的參數名稱必須與字典中的鍵名稱匹配。
2. 參數的數量應與字典中的鍵的數量相同。
* * *
* * *
- 初級 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 轉儲對象