Convert string into a function call

前端 未结 1 592
终归单人心
终归单人心 2020-12-10 06:25

I have a string variable with the exact name of a function, e.g.

ran_test_opt = \"random_aoi\"

The function looks like this:



        
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 06:29

    Sure, you can use globals:

    func_to_run = globals()[ran_test_opt]
    func_to_run()
    

    Or, if it is in a different module, you can use getattr:

    func_to_run = getattr(other_module, ran_test_opt)
    func_to_run()
    

    0 讨论(0)
提交回复
热议问题