2012-02-18 103 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) 
相關問題