简体   繁体   English

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

[英]Can method 1 pass kwargs to method 2?

I want kwargs to have the same exact contents in method2 as whatever gets passed into method1. 我希望kwarg在method2中具有与传递到method1中的内容完全相同的确切内容。 In this case "foo" is passed into method1 but I want to pass in any arbitrary values and see them in kwargs in both method1 and method2. 在这种情况下,“ foo”被传递给method1,但是我想传递任意值,并在method1和method2的kwargs中看到它们。 Is there something I need to do differently with how I call 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)

Output: 输出:

method1 has foo in kwargs

Desired output: 所需的输出:

method1 has foo in kwargs
method2 has foo in kwargs

Let me know if I need to clarify what I'm asking, or if this is not possible. 让我知道是否需要澄清我的要求,或者是否无法做到。

关键字扩展。

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

    method2(**kwargs)

It's called unpacking argument lists. 这称为解压缩参数列表。 The python.org doc is here . python.org文档在这里 In your example, you would implement it like this. 在您的示例中,您将像这样实现它。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM