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'