方法1可以将kwargs传递给方法2吗?

时间:2012-02-18 03:08:45

标签: python kwargs

我希望kwargs在method2中具有与传递给method1的内容完全相同的内容。在这种情况下,“foo”被传递给method1,但我想传入任意值,并在method1和method2中的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

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

3 个答案:

答案 0 :(得分:3)

Keyword expansion.

method2(**kwargs)

答案 1 :(得分:2)

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

    method2(**kwargs)

答案 2 :(得分:1)

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

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)