方法1可以将kwargs传递给方法2吗?
我希望 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关键字扩展。
Keyword expansion.
这称为解包参数列表。 python.org 文档位于此处。在您的示例中,您将像这样实现它。
It's called unpacking argument lists. The python.org doc is here. In your example, you would implement it like this.