我在函数中有很多函数和很多变量,因为我正在制作模块化的 2D 绘图。为此,我希望能够将 kwargs 字典向下传递到多个函数层中。例如:
mydict = {'a':1,'b':2,'c':3}
def bar(b, c, **kwargs):
print("bar b=" + str(b))
print("bar c=" + str(c))
print("bar kwargs: ", kwargs)
def foo(a, b, **kwargs):
print("foo a=" + str(a))
print("foo b=" + str(b))
print("foo kwargs: ", kwargs)
bar(b, **kwargs)
foo(**mydict)
返回:
foo a=1
foo b=2
foo kwargs: {'c': 3}
bar b=2
bar c=3
bar kwargs: {}
这很好用,因为它捕获了我不需要的所有 kwargs。但是,我需要明确地将我在 foo
中解压的 kwargs 传递给 bar
。我想将整个 mydict
传递到 bar
中,就像我在 foo
中所做的那样,同时保持它的可读性。
我现在能想到的唯一方法是传递 mydict
两次,我只解压一次并在 **_
中捕获任何未使用的 kwargs,这看起来不太好。
mydict = {'a':1,'b':2,'c':3}
def bar(mydict, b, c, **_):
print("bar b=" + str(b))
print("bar c=" + str(c))
print("bar \'kwargs\': ", mydict)
def foo(mydict, a, b, **_):
print("foo a=" + str(a))
print("foo b=" + str(b))
print("foo \'kwargs\': ", mydict)
bar(mydict, **mydict)
foo(mydict, **mydict)
哪个返回
foo a=1
foo b=2
foo 'kwargs': {'a': 1, 'b': 2, 'c': 3}
bar b=2
bar c=3
bar 'kwargs': {'a': 1, 'b': 2, 'c': 3}
有没有更好的方法来做到这一点?
最佳答案
让函数只接受**kwargs:
mydict = {'a':1,'b':2,'c':3}
def bar(**kwargs):
print("bar b=" + str(kwargs['b']))
print("bar c=" + str(kwargs['c']))
print("bar kwargs: ", kwargs)
def foo(**kwargs):
print("foo a=" + str(kwargs['a']))
print("foo b=" + str(kwargs['b']))
print("foo kwargs: ", kwargs)
bar(**kwargs)
foo(**mydict)
https://stackoverflow.com/questions/72793593/