【问题标题】:generate keyword arguments from positional arguments in python从python中的位置参数生成关键字参数
【发布时间】:2019-12-03 14:52:18
【问题描述】:

给定一个函数定义

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}

这样好吗?

【问题讨论】:

  • 使用locals() 获取局部变量字典?这对你有用吗?

标签: python args keyword-argument


【解决方案1】:

您不需要model=model 位。参数是位置的,它们根据它们的顺序匹配,不一定是它们的名字。在通话现场不要等价。

>>> def foo(bar, baz):
...     print('bar',bar,'baz',baz)
... 
>>> bar=2
>>> baz=3
>>> foo(bar,baz)
bar 2 baz 3

有关位置参数的更多信息:Positional argument v.s. keyword argument

如果您只想将 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

【讨论】:

  • 是的,我知道,但我需要能够以任意顺序和组合传递参数,这使您的解决方案不可行
  • 我试图将该代码放在评论中,但它不可读。我将代码放入答案的编辑中。它使用 REPL 样式。希望有帮助。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2017-05-21
  • 2012-11-21
  • 2020-11-18
  • 1970-01-01
相关资源
最近更新 更多