简体   繁体   中英

Python: pass more than one keyword argument?

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

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

You only need one keyword-arguments parameter; it receives any number of keyword arguments.

def foo(**kwargs):
  return kwargs

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

I would write a function to do this for you

 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

You can then use it like this

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

This will get them into two separate dicts. It doesn't make any sense for python to provide this behavior as you have to manually specify which dict you want them to end up in. Another alternative is to just manually specify it in the function definition

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

Now you have one dict for the ones you don't specify and regular local variables for the ones you do want to name.

You cannot. But keyword arguments are dictionaries and when calling you can call as many keyword arguments as you like. They all will be captured in the single **kwarg . Can you explain a scenario where you would need more than one of those **kwarg in the function definition?

>>> 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']

Maybe this helps. Can you clarify how the kw arguments are divided into the two dicts?

>>> 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}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM