2011-01-11 89 views
0

是否有可能將多個關鍵字參數傳遞給python中的函數?Python:傳遞多個關鍵字參數?

foo(self, **kwarg)  # Want to pass one more keyword argument here 
+0

正如克里斯所說,你的函數可以接受任意數量的關鍵字參數而不做任何改變。 – 2011-01-11 02:37:18

+0

你在做什麼需要這個? – detly 2011-01-11 03:05:12

回答

2

我會寫一個函數來爲你做這個

def partition_mapping(mapping, keys): 
    """ Return two dicts. The first one has key, value pair for any key from the keys 
     argument that is in mapping and the second one has the other keys from    
     mapping 
    """ 
    # This could be modified to take two sequences of keys and map them into two dicts 
    # optionally returning a third dict for the leftovers 
    d1 = {} 
    d2 = {} 
    keys = set(keys) 
    for key, value in mapping.iteritems(): 
     if key in keys: 
      d1[key] = value 
     else: 
      d2[key] = value 
    return d1, d2 

然後,您可以使用它像這樣

def func(**kwargs): 
    kwargs1, kwargs2 = partition_mapping(kwargs, ("arg1", "arg2", "arg3")) 

這將讓他們分成兩個獨立的類型的字典。它沒有任何意義的,你必須手動指定您希望他們在結束該字典Python來提供這種行爲。另一種方法是在函數定義只是手工指定它現在

def func(arg1=None, arg2=None, arg3=None, **kwargs): 
    # do stuff 

你有一個你沒有指定的字典和你想要命名的常規局部變量。

5

您只需要一個關鍵字參數參數;它會收到任意個關鍵字參數。

def foo(**kwargs): 
    return kwargs 

>>> foo(bar=1, baz=2) 
{'baz': 2, 'bar': 1} 
+0

我只是希望他們在兩個單獨的字典。 – user469652 2011-01-11 02:36:07

1

你不能。但關鍵字參數是字典,當你打電話時,你可以根據需要調用盡可能多的關鍵字參數。它們全部將被捕獲在單個**kwarg中。你能解釋一個場景,你需要在函數定義中的多個**kwarg嗎?

>>> def fun(a, **b): 
...  print b.keys() 
...  # b is dict here. You can do whatever you want. 
...  
...  
>>> fun(10,key1=1,key2=2,key3=3) 
['key3', 'key2', 'key1'] 
1

也許這有助於。你能否澄清一下kw的論點是如何分解爲兩個詞的?

>>> def f(kw1, kw2): 
... print kw1 
... print kw2 
... 
>>> f(dict(a=1,b=2), dict(c=3,d=4)) 
{'a': 1, 'b': 2} 
{'c': 3, 'd': 4}