2015-07-03 48 views
7

我知道Python中函數定義中星號的含義。帶星號參數且不帶有差異呼叫功能

我經常,不過,看到函數調用中星號與參數,如:

def foo(*args, **kwargs): 
    first_func(args, kwargs) 
    second_func(*args, **kwargs) 

是什麼第一和第二函數調用的區別?

+1

星號取變量出括號的:) – LittleQ

+0

的可能重複的[瞭解Python中的kwargs](http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python) –

回答

11

arg = [1,2,3]

func(*arg) == func(1,2,3)變量出來列表(或療法序列類型)作爲參數

func(arg) == func([1,2,3])一個不勝枚舉在

kwargs = dict(a=1,b=2,c=3)

func(kwargs) == func({'a':1, 'b':2, 'c':3})一個字典進去

func(**kwargs) == func(a=1,b=2,c=3)(鍵,值)來字典(或其他映射類型)的出作爲命名的參數

+0

一個很好的簡單答案。謝謝。 –

+0

真的很好回答:+1!你可以添加並解釋'func(* kwarg)'的情況嗎? – winklerrr

4

區別在於參數是如何傳遞到被調用函數的。當您使用*時,參數將被解壓縮(如果它們是列表或元組)—否則,它們只是按原樣傳入。

區別在這裏的一個例子:

>>> def add(a, b): 
... print a + b 
... 
>>> add(*[2,3]) 
5 
>>> add([2,3]) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: add() takes exactly 2 arguments (1 given) 
>>> add(4, 5) 
9 

當我爲前綴的說法與*,它實際上解壓列表分爲兩個獨立的參數,這些參數被傳遞到addab。沒有它,它只是作爲單個參數傳入列表中。

字典和**的情況也是如此,除了它們是作爲命名參數而不是有序參數傳遞的。

>>> def show_two_stars(first, second='second', third='third'): 
... print "first: " + str(first) 
... print "second: " + str(second) 
... print "third: " + str(third) 
>>> show_two_stars('a', 'b', 'c') 
first: a 
second: b 
third: c 
>>> show_two_stars(**{'second': 'hey', 'first': 'you'}) 
first: you 
second: hey 
third: third 
>>> show_two_stars({'second': 'hey', 'first': 'you'}) 
first: {'second': 'hey', 'first': 'you'} 
second: second 
third: third 
+0

謝謝你的詳細答案。這對我非常有幫助。 –

0
def fun1(*args): 
    """ This function accepts a non keyworded variable length argument as a parameter. 
    """ 
    print args   
    print len(args) 


>>> a = [] 

>>> fun1(a) 
([],) 
1 
# This clearly shows that, the empty list itself is passed as a first argument. Since *args now contains one empty list as its first argument, so the length is 1 
>>> fun1(*a) 
() 
0 
# Here the empty list is unwrapped (elements are brought out as separate variable length arguments) and passed to the function. Since there is no element inside, the length of *args is 0 
>>> 
+0

我想你的答案會更清楚,如果你已經添加了一些值'a' – winklerrr

+0

這個例子是爲了顯示args解包的工作方式。如果你有一個元素添加到'a'並傳遞給args而沒有解包,那麼args的長度將是1.對於第一種情況,它會是(['some val']),對於第二種情況,它會是('一些val') – user2126456