python 在python中传递命名变量参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing on named variable arguments in python
提问by Staale
Say I have the following methods:
说我有以下方法:
def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define methodA
as follows, the second argument will be passed on as positional rather than named variable arguments.
在方法A中,我希望调用方法B,传递kwargs。但是,似乎如果我methodA
如下定义,第二个参数将作为位置参数而不是命名变量参数传递。
def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?
如何确保methodA中的**kwargs作为**kwargs传递给methodB?
回答by Cristian
Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.
将星号放在 kwargs 变量之前。这使得 Python 将变量(假定为字典)作为关键字参数传递。
methodB("argvalue", **kwargs)
回答by Sebastian Rittau
As an aside: When using functions instead of methods, you could also use functools.partial:
顺便说一句:当使用函数而不是方法时,你也可以使用 functools.partial:
import functools
def foo(arg, **kwargs):
...
bar = functools.partial(foo, "argvalue")
The last line will define a function "bar" that, when called, will call foo with the first argument set to "argvalue" and all other functions just passed on:
最后一行将定义一个函数“bar”,当调用该函数时,将调用 foo 并将第一个参数设置为“argvalue”,并且所有其他函数刚刚传递:
bar(5, myarg="value")
will call
将会通知
foo("argvalue", 5, myarg="value")
Unfortunately that will not work with methods.
不幸的是,这不适用于方法。
回答by Staale
Some experimentation and I figured this one out:
一些实验,我想出了这个:
def methodA(arg, **kwargs): methodB("argvalue", **kwargs)
def methodA(arg, **kwargs): methodB("argvalue", **kwargs)
Seems obvious now...
现在看起来很明显...