Python:传递多个关键字参数?

时间:2011-01-11 02:30:53

标签: python

是否可以将多个关键字参数传递给python中的函数?

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

4 个答案:

答案 0 :(得分:5)

您只需要一个keyword-arguments参数;它接收任何个关键字参数。

def foo(**kwargs):
  return kwargs

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

答案 1 :(得分: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提供此行为没有任何意义,因为您必须手动指定您希望它们最终进入哪个dict。另一种方法是在函数定义中手动指定它

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

现在你有一个你没有指定的dict和你想要命名的常规局部变量。

答案 2 :(得分: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']

答案 3 :(得分: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}