我有一本这样的字典:
dictionary = { "a":function_1(), "b":function_2(), "c":function_3()}
但是由于我不想在声明字典时运行所有函数,因此将它们存储为字符串:
dictionary = { "a":"function_1()", "b":"function_2()", "c":"function_3()"}
我想做的只是基于与之关联的键来调用一个函数:
for key,value in dictionary.items():
if key == something:
wanted_variable = value
如果现在打印我想要的变量,它将返回“ function_1()”,而我希望它是function_1()返回的内容...
有人可以帮我吗?
答案 0 :(得分:4)
由于函数是一类对象,因此您可以传递对它们的引用而无需调用它们,以后再调用它们:
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"
答案 1 :(得分:3)
您可以存储函数而无需调用:
dictionary = { "a":function_1, "b":function_2, "c":function_3} # no ()
之后
for key, value in dictionary.items():
if key == something:
wanted_variable = value()
顺便说一下,有一种更有效的获取wanted_variable
的方法:
if something in dictionary:
wanted_variable = dictionary[something]()
答案 2 :(得分:2)
您只需要用函数名定义字典:
dictionary = {"a":function_1, "b":function_2, "c":function_3}
如果在函数名称后加上括号,则立即调用它。
调用所需的匹配函数为:
for key, value in dictionary.items():
if key == 'a':
wanted_variable = value()
答案 3 :(得分:2)
您可以只存储函数而无需调用它们:
dictionary = { "a":function_1, "b":function_2, "c":function_3}
然后:
for key,value in dictionary.items():
if key == something:
wanted_variable = value()
答案 4 :(得分:1)
您可以存储不带()的函数,这样它们就不会执行,那么您可以这样做:
def func1():
x = "func1"
print(x)
return x
def func2():
x = "func2"
print(x)
return x
d = {"a":func1, "b":func2}
wanted_variable = d["a"]()
答案 5 :(得分:0)
eval
是针对您这个问题的更简单和实际的答案。
dictionary = { "a":"function_1()", "b":"function_2()", "c":"function_3()"}
for key, value in dictionary.items():
if key == something:
wanted_variable = eval(value)