How to convert a string to a function name in python?

前端 未结 9 2081
迷失自我
迷失自我 2020-11-27 12:55

For example, if I have a function called add like

def add(x,y):
    return x+y

and I want the ability to convert a string or a

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 13:22

    unutbu's solution is what I would normally use, but for completeness sake:

    If you are specifying the exact name of the function, you can use eval, although it is highly discouraged because people can do malicious things:

    eval("add")(x,y)
    

提交回复
热议问题