python的*args与**kwargs
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