【问题标题】:Convert string into a function call withing the same class将字符串转换为同一个类中的函数调用
【发布时间】:2014-02-26 11:40:08
【问题描述】:

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

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

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

KeyError: 'random_aoi' 

【问题讨论】:

    标签: python string function call


    【解决方案1】:

    不要使用globals()(函数不在全局符号表中),使用getattr即可:

    ran_test_func = getattr(self, ran_test_opt)
    

    【讨论】:

      【解决方案2】:

      globals() 是一个你应该非常、非常少使用的函数,它有混合代码和数据的味道。通过在字符串中找到的名称调用实例方法是类似的,但不那么 hacky。使用getattr

      ran_test_func = getattr(self, ran_test_opt)
      ran_test_func()
      

      【讨论】:

        猜你喜欢
        • 2014-03-28
        • 2020-07-27
        • 1970-01-01
        • 1970-01-01
        • 2020-05-21
        • 1970-01-01
        • 2018-11-24
        相关资源
        最近更新 更多