将字符串转换为同一类中的函数调用

时间:2014-02-26 11:40:09

标签: python string function call

如何将字符串转换为函数调用以获取同一类中的函数?我使用this问题来帮助我,但我认为它与“自我”有关。

ran_test_opt = choice(test_options)
ran_test_func = globals()[ran_test_opt]
ran_test_func()

其中test_options是字符串格式的可用函数名称列表。使用上面的代码我得到了错误

KeyError: 'random_aoi' 

2 个答案:

答案 0 :(得分:3)

不要使用globals()(函数不在全局符号表中),只需使用getattr

ran_test_func = getattr(self, ran_test_opt)

答案 1 :(得分:1)

globals()是一个非常非常罕见的函数,它混合了代码和数据。通过在字符串中找到的名称调用实例方法是类似的,但稍微不那么hacky。使用getattr

ran_test_func = getattr(self, ran_test_opt)
ran_test_func()