python - 从 python 中的位置参数生成关键字参数

标签 python args keyword-argument

给定一个函数定义

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 位。参数是位置性的,它们根据它们的顺序匹配,不一定是它们的名字。在调用站点省略 equals。

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

如果你只想将一个字典传递给一个对象,你可以使用 **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

关于python - 从 python 中的位置参数生成关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159752/

相关文章:

Python 在格式化字符串 : expect string, 中使用 kwargs get dict?

python - latex 符号不适用于 pycharm 2016.3

python - Tensorflow 没有正式命名的模块

Python 习语 - *arg/**kwargs 中的空格

python - Scipy.optimize check_grad 函数给出 "Unknown keyword arguments: [' args']"错误

Python nosetests : how to access cmd line options? 即 `--failed`

python - 如何使用 Tableau 或 Excel 将数据时间转换为秒数

python - Pandas GroupBy - 仅显示具有多个独特特征值的组

python - 如何调用包含带有输入函数数据的 kwargs 的函数?

python - 使用函数接受不是标识符的 kwargs 关键字参数是否安全?