由于函数是第一类对象,您可以在不调用它们的情况下传递对它们的引用,并在以后调用它们:
dictionary = {
"a":function_1, # No parens here anymore
"b":function_2, # ''
"c":function_3, # ''
}
for key,value in dictionary.items():
if key == something:
# "Calling" parens here, not in the dictionary values
wanted_variable = value()
或者,
dictionary = {
"a":function_1, # No parens here anymore
"b":function_2, # ''
"c":function_3, # ''
}
func = dictionary.get(key)
if func:
wanted_variable = func()
最终会做同样的事情,但不必遍历字典项。
对于更复杂的场景,当你想要捕获一个未调用的函数但也该函数的参数时,还有functools.partial
from functools import partial
dictionary = {
"a":partial(function_1, 123),
"b":partial(function_2, 456),
"c":partial(function_3, 789),
}
for key,value in dictionary.items():
if key == something:
# "Calling" parens here, not in the dictionary values
# This will actually call, for example, function_1(123).
wanted_variable = value()
例如:
from functools import partial
def foo(x):
print("x is", x)
wrapped_foo = partial(foo, 123)
# Pass wrapped_foo around however you want...
d = {'func': wrapped_foo}
# Call it later
d['func']() # Prints "foo is 123"