简体   繁体   English

在python中传递命名变量参数

[英]Passing on named variable arguments in python

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. 在methodA中,我希望调用methodB,传递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 ,则第二个参数将作为位置而不是命名变量参数传递。

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?

Put the asterisks before the kwargs variable. 把星号放在kwargs变量之前。 This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments. 这使得Python将变量(假定为字典)作为关键字参数传递。

methodB("argvalue", **kwargs)

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. 不幸的是,这不适用于方法。

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... 现在似乎显而易见......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM