Python:从字典中运行代码

A.L*_*Lex 2 python dictionary

字典是从配置文件生成的:

    dict_1 = {
            'type1' : 'function1()',
            'type2' : 'function2()',
            'type3' : 'function3()'
        }
Run Code Online (Sandbox Code Playgroud)

变量x包含此字典中的任何键.我试着按如下方式调用函数:

dict_1[x]
Run Code Online (Sandbox Code Playgroud)

有没有人知道运行此语句的exec函数的替代方法?

idj*_*jaw 5

正如评论中所提到的,为了帮助您更好地说明这一点,这是您最好的方法:

def foo():
    print("I was just called")

def boo():
   print("I was called too")


dict_of_methods = {
    "type1": foo,
    "type2": boo
}

dict_of_methods.get('type1')()
dict_of_methods.get('type2')()
Run Code Online (Sandbox Code Playgroud)

如果您在字典中处理了该方法的字符串表示形式,那么在使用以下两个命令时,您必须对本地和全局范围保持谨慎,但您的选项如下:

locals()[dict_of_methods.get('type1')]()

globals()[dict_of_methods.get('type1')]()
Run Code Online (Sandbox Code Playgroud)

阅读本文以了解:

http://www.diveintopython.net/html_processing/locals_and_globals.html