2011-01-11 85 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}