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.
在methodA中,我希望调用methodB,传递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?
3 个解决方案
#1
33
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)
#2
2
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.
不幸的是,这不适用于方法。
#3
1
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...
现在似乎显而易见......
#1
33
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)
#2
2
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.
不幸的是,这不适用于方法。
#3
1
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...
现在似乎显而易见......