2009-07-24 27 views
4

可能重複:
What does *args and **kwargs mean?在傳遞參數的時候,python在參數前做了什麼?

從閱讀這個例子中,並從我的Python它的纖薄的知識必須是一個數組轉換詞典之類的快捷方式?

class hello: 
    def GET(self, name): 
     return render.hello(name=name) 
     # Another way: 
     #return render.hello(**locals()) 
+0

確切複製http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean – SilentGhost 2009-07-24 18:05:27

回答

1

它將字典「解包」爲參數列表。 即:

def somefunction(keyword1, anotherkeyword): 
    pass 

它可以被稱爲

somefunction(keyword1=something, anotherkeyword=something) 
or as 
di = {'keyword1' : 'something', anotherkeyword : 'something'} 
somefunction(**di) 
11

在蟒f(**d)通過在詞典中作爲d關鍵字參數的值,以該函數f。類似地,f(*a)傳遞來自數組a的值作爲位置參數。

作爲一個例子:

def f(count, msg): 
    for i in range(count): 
    print msg 

調用帶**d*a此功能:

>>> d = {'count': 2, 'msg': "abc"} 
>>> f(**d) 
abc 
abc 
>>> a = [1, "xyz"] 
>>> f(*a) 
xyz 
1

Python docuemntation, 5.3.4

如果任何關鍵字參數不對應於正式的參數名稱,會引發TypeError異常,除非有正式的p使用語法**標識符的參數存在;在這種情況下,該形式參數將接收包含多餘關鍵字參數(使用關鍵字作爲關鍵字並將參數值作爲相應值)的字典,如果沒有多餘的關鍵字參數,則會接收(新)空字典。

這也用於the power operator,在不同的上下文中。

1

** local()傳遞對應於調用者本地名稱空間的字典。當通過**傳遞函數時,會傳遞一個字典,這允許可變長度的參數列表。

相關問題