0

我希望 kwargs 在 method2 中具有与传入 method1 的内容相同的确切内容。在这种情况下,“foo”被传递到方法 1,但我想传递任意值并在方法 1 和方法 2 中的 kwargs 中查看它们。我需要对我如何调用 method2 做一些不同的事情吗?

def method1(*args,**kwargs):

    if "foo" in kwargs:
        print("method1 has foo in kwargs")

    # I need to do something different here
    method2(kwargs=kwargs)

def method2(*args,**kwargs):

    if "foo" in kwargs:
        # I want this to be true
        print("method2 has foo in kwargs")

method1(foo=10)

输出:

method1 has foo in kwargs

期望的输出:

method1 has foo in kwargs
method2 has foo in kwargs

如果我需要澄清我在问什么,或者如果这是不可能的,请告诉我。

4

3 回答 3

3

关键字扩展。

method2(**kwargs)
于 2012-02-18T03:11:13.980 回答
2
def method1(*args,**kwargs):
    if "foo" in kwargs:
        print("method1 has foo in kwargs")

    method2(**kwargs)
于 2012-02-18T03:10:58.330 回答
1

它被称为解包参数列表。python.org 文档在这里。在您的示例中,您将像这样实现它。

def method1(*args,**kwargs):      
    if "foo" in kwargs:         
        print("method1 has foo in kwargs")      

    # I need to do something different here     
    method2(**kwargs) #Notice the **kwargs.  

def method2(*args,**kwargs):      
    if "foo" in kwargs:         # I want this to be true         
        print("method2 has foo in kwargs")  

method1(foo=10)
于 2012-02-18T03:15:44.550 回答