簡體   English   中英

Python:傳遞多個關鍵字參數?

[英]Python: pass more than one keyword argument?

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

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

您只需要一個關鍵字參數參數即可; 它接收任意數量的關鍵字參數。

def foo(**kwargs):
  return kwargs

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

我會寫一個函數為你做

 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

現在,您可以為未指定的對象指定一個字典,為要命名的對象指定常規的局部變量。

你不能。 但是關鍵字參數是字典,在調用時,您可以根據需要調用任意多個關鍵字參數。 它們都將被捕獲在單個**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']

也許這會有所幫助。 您能否闡明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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM