[英]Python: send arguments to function in dictionary
Is it possible to pass arguments to a function within a dictionary? 是否可以将参数传递给字典中的函数?
d = {"A": foo(), "B": bar()}
def foo(arg):
return arg + 1
def bar(arg):
return arg - 1
In this case I want to pass arg to bar() by referencing the function dynamically 在这种情况下,我想通过动态引用函数将arg传递给bar()
d["B"] #<-- pass arg to bar()
It's possible, but you have to refer to the function (eg foo
) without already calling it (eg foo()
). 有可能,但是您必须引用函数(例如foo
)而不必调用它(例如foo()
)。
def foo(arg):
return arg + 1
def bar(arg):
return arg - 1
d = {"A": foo, "B": bar}
Result: 结果:
>>> d['A'](5)
6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.