2012-02-18 109 views
0

我想让kwargs在method2中拥有与传递给method1相同的确切内容。在这种情况下,“foo”传递给method1,但我想传入任意值,并在method1和method2中的kwargs中看到它们。有什么我需要做的与我如何调用method2不同吗?方法1是否可以将kwargs传递给方法2?

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 

让我知道如果我要澄清,我问什么,或者如果这是不可能的。

回答

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

    method2(**kwargs) 
1

这就是所谓的拆包参数列表。 python.org文档是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)