Способ 1 может передать kwargs методу 2? - PullRequest
0 голосов
/ 18 февраля 2012

Я хочу, чтобы у kwargs было то же самое точное содержимое в method2, что и все, что передается в method1.В этом случае «foo» передается в method1, но я хочу передать любые произвольные значения и увидеть их в kwargs в method1 и method2.Есть ли что-то, что мне нужно сделать по-другому с тем, как я вызываю 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 ]

3 голосов
/ 18 февраля 2012
2 голосов
/ 18 февраля 2012
def method1(*args,**kwargs):
    if "foo" in kwargs:
        print("method1 has foo in kwargs")

    method2(**kwargs)
1 голос
/ 18 февраля 2012

Это называется распаковкой списков аргументов. Документ 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)
...