Python 中的 *args and **kwargs(關鍵詞:Python/)
阿新 • • 發佈:2018-12-09
*
和 **
讓函式支援接收任意數目的引數,有函式定義和函式呼叫這 2 種情況。
在函式定義中,
(1)*args
收集任意多的 位置引數 到 1 個元組 args
中;
(2)**kwargs
收集任意多的 關鍵字引數 到 1 個字典 kwargs
中;
(3)還可以混合位置引數、*
、**
任意引數,實現靈活的呼叫。
在函式呼叫中,
(4)*args
可以 解包 元組、列表 args
;
(5)**kwargs
可以 解包 字典 kwargs
。
Python 3 中的 keyword-only 引數,
(6)在 Python 2 中會報錯;
(7)出現在 *b
前面的引數可以按照位置或關鍵字來傳遞,b收集額外的位置引數到 1 個元組,*b
(8)在引數列表中使用
*
,出現在 *
之前的引數按照位置或關鍵字來傳遞,*
之後的引數必須只按照關鍵字來傳遞。
# (1) >>> def f1(*args): print args >>> f() () >>> f1(1) (1,) >>> f1(1, 2) (1, 2) >>> f1(1, 2, 3) (1, 2, 3) # (2) >>> def f2(**kwargs): print kwargs >>> f() {} >>> f2(a=2) {'a': 2} >>> f2(a=2, b=4) {'a': 2, 'b': 4} # (3) >>> def f3(a, *pargs, **kwargs): print a, pargs, kwargs >>> f3(1, 2, 3, b=4, c=5) 1 (2, 3) {'c': 5, 'b': 4} # (4) >>> def f4(a, b, c): print a, b, c >>> args = (1, 2, 3) >>> f4(*args) 1 2 3 >>> args = [1, 2, 3] >>> f4(*args) 1 2 3 >>> kwargs = {'a':6, 'b':4, 'c':8} >>> kwargs.keys() ['a', 'c', 'b'] >>> f4(*kwargs) a c b # (5) >>> def f4(a, b, c): print a, b, c >>> kwargs = {'a':6, 'b':4, 'c':8} >>> f4(**kwargs) 6 4 8
# (6)Python 2 下會報錯
>>> def f6(a, *b, c):
print a, b, c
SyntaxError: invalid syntax
# (7) >>> def f6(a, *b, c): print(a, b, c) >>> f6(1, 2, c=3) 1 (2,) 3 >>> f6(a=1, c=3) 1 () 3 >>> f6(1, 2, 3) Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> f6(1, 2, 3) TypeError: f6() missing 1 required keyword-only argument: 'c'
# (8)
>>> def f8(a, *, b, c):
print(a, b, c)
>>> f8(1, b=2, c=3)
1 2 3
>>> f8(a=1, b=2, c=3)
1 2 3
>>> f8(1, 2, 3)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
f8(1, 2, 3)
TypeError: f8() takes 1 positional argument but 3 were given
參考文獻:
- 《Python 學習手冊(第 4 版)》 - 第 18 章 引數 - 特定的引數匹配模型 - P449——P471。