[英]generate keyword arguments from positional arguments in python
給定函數定義
def foo(model, evaluator):
pass
model = ...
evaluator = ...
和這樣的呼叫站點
foo(model=model, evaluator=evaluator)
我只想做
foo(model, evaluator)
以避免重復,然后在 foo 中構造關鍵字參數,以便以后傳遞給 **kwargs 參數。
我能想到的唯一方法是
def foo(*args):
**{str(arg): arg for arg in args}
這個可以嗎?
您不需要model=model
位。 參數是位置性的,它們根據它們的順序匹配,不一定是它們的名字。 在呼叫站點不要使用等號。
>>> def foo(bar, baz):
... print('bar',bar,'baz',baz)
...
>>> bar=2
>>> baz=3
>>> foo(bar,baz)
bar 2 baz 3
有關位置參數的更多信息: 位置參數與關鍵字參數
如果只想將 dict 傳遞給對象,則可以使用 **arg 語法:
>>> def show_me(**m):
... for k,v in m.items():
... print(k,v)
>>> d={'x':2,'y':3}
>>> show_me(**d)
x 2
y 3
你可以用雙星號 **d 調用它:
>>> show_me(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: show_me() takes 0 positional arguments but 1 was given
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.