1、**的作用
首先是一个简单的例子,定义一个带有3个参数的函数
def fun(a, b, c):
print a, b, c
这个函数可以使用多种方法进行调用
fun(1,2,3) 输出:1 2 3 fun(1, b=4, c=6) 输出:1 4 6
接下来使用**来进行函数调用,首先需要一个字典,就像使用*进行函数调用时需要列表或者元组一样
d={'b':5, 'c':7}
fun(1, **d)
执行之后的输出为:1 5 7
我们可以看到,在这里**的作用是将传入的字典进行unpack,然后将字典中的值作为关键词参数传入函数中。
所以,在这里fun(1, **d)就等价于fun(1, b=5, c=7)
更多的例子
d={'c':3} fun(1,2,**d) d={'a':7,'b':8,'c':9} fun(**d)
#错误的例子 d={'a':1, 'b':2, 'c':3, 'd':4} fun(**d)
上面的代码会报错:
TypeError: fun() got an unexpected keyword argument 'd'
2、**kwargs的作用
重新定义我们的fun函数
def fun(a, **kwargs): print a, kwargs
这个函数因为形参中只有一个a,所以只有一个positional argument。
但是却有一个可以接收任意数量关键词参数的kwargs。
使用**kwargs定义参数时,kwargs将会接收一个positional argument后所有关键词参数的字典。
def fun(a, **kwargs): print "a is", a print "We expect kwargs 'b' and 'c' in this function" print "b is", kwargs['b'] print "c is", kwargs['c']
fun(1, b=3, c=5)
输出是:
a is 1 We expect kwargs 'b' and 'c' in this function b is 3 c is 5
错误的调用:
fun(1, b=3, d=5) a is 1 We expect kwargs 'b' and 'c' in this function b is 3 c is--------------------------------------------------------------------------- KeyError Traceback (most recent call last) xxxxx in <module>() xxxxx in fun(a, **kwargs) KeyError: 'c'