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

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

    One safe way is to map from names to functions. It's safer than using eval.

    function_mappings = {
            'add': add,
    }
    
    def select_function():
        while True:
            try:
                return function_mappings[raw_input('Please input the function you want to use')]
            except KeyError:
                print 'Invalid function, try again.'
    

提交回复
热议问题