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

发布于 2025-01-07 12:12:03 字数 690 浏览 0 评论 0原文

我希望 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

如果我需要澄清我的要求,或者这是否不可能,请告诉我。

I want kwargs to have the same exact contents in method2 as whatever gets passed into 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. Is there something I need to do differently with how I call 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

三月梨花 2025-01-14 12:12:03

关键字扩展。

method2(**kwargs)

Keyword expansion.

method2(**kwargs)
久伴你 2025-01-14 12:12:03
def method1(*args,**kwargs):
    if "foo" in kwargs:
        print("method1 has foo in kwargs")

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

    method2(**kwargs)
倾城月光淡如水﹏ 2025-01-14 12:12:03

这称为解包参数列表。 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)

It's called unpacking argument lists. The python.org doc is here. 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文