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

前端 未结 9 2051
迷失自我
迷失自我 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:28

    The built-in function eval will do what you want. All the usual warnings about executing arbitrary user-supplied code apply.

    If there are a finite number of predefined functions, you should avoid eval and use a lookup table instead (i.e. Dict). Never trust your users.

提交回复
热议问题