以字符串形式存储到运行

2024-04-25 15:08:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典:

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\u 1()”,我希望它是function\u 1()返回的。。。你知道吗

有人能帮我吗?你知道吗


Tags: key函数字符串in声明fordictionaryif
3条回答

由于函数是第一类对象,因此可以在不调用函数的情况下传递对它们的引用,然后再调用它们:

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()

结果是做同样的事情,但不必循环浏览字典中的条目。你知道吗

对于更复杂的场景,当您想要捕获一个未调用的函数,但同时捕获该函数的参数时,还有^{}

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"

只需使用函数名定义字典:

dictionary = {"a":function_1, "b":function_2, "c":function_3}

如果在函数名后面加上一个括号,就可以立即调用它。你知道吗

调用所需的函数匹配为:

for key, value in dictionary.items():
     if key == 'a':
          wanted_variable = value()

无需调用即可存储函数:

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]()

相关问题 更多 >