1. 程式人生 > >python的*args與**kwargs

python的*args與**kwargs

std ack mod 列表 -s lin AD module str

1. *args 允許將一個非鍵值對的可變數量的參數列表(元組)傳遞給一個函數。

>>> def add(*args):
...     return sum(args)
...
>>> add(1,2,3,4)
10
>>> a = (1,2,3,4)
>>> add(a) # 錯誤,等價於sum(((1,2,3,4),)),即將元組a與0相加
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File 
"<stdin>", line 2, in add TypeError: unsupported operand type(s) for +: int and tuple >>> add(*a) 10 >>> sum(((1,2,3,4),)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: int and tuple

2. **kwargs 允許將一個鍵值對的可變數量的參數字典傳遞給一個函數。

>>> def add(**kwargs):
...     return sum(kwargs.values())
...
>>> add(a=1,b=2,c=3)
6

綜合:

>>> def f(arg,*args,**kwargs):
...     print(arg)
...     print(args)
...     print(kwargs)
...
>>> f(1,*(1,2,3,4),**{"a":1,"b":2,"
c":3}) 1 (1, 2, 3, 4) {b: 2, c: 3, a: 1} >>> f(1,1,2,3,4,a=1,b=2,c=3) # 與上面效果一樣

調用時

def func(a,b,c,d):
    print(a,b,c,d)

args = (1,2,3,4)
func(*args)
1,2,3,4

def func(a,b,c,d):
    print(a,b,c,d)

kargs = {a:1, b:2, c:3, d:4}
func(**kargs)
1,2,3,4

python的*args與**kwargs