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

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

    Just use function reference:

    def pwr(x, y):
        return x ** y
    
    def add(x, y):
        return x + y
    
    dispatcher = { 'pwr' : pwr, 'add' : add}
    
    def call_func(x, y, func):
        try:
            return dispatcher[func](x, y)
        except:
            return "Invalid function"
    
    call_func(2, 3, 'add')
    

    Simple and secure.

提交回复
热议问题