How to convert a string to a function in python?
问题 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 an input to direct to that function like w=raw_input('Please input the function you want to use') or w='add' Is there any way to use w to refer to the function add? 回答1: Since you are taking user input, the safest way is to define exactly what is valid input: dispatcher={'add':add} w='add' try: function=dispatcher[w] except KeyError: raise ValueError('invalid input') If you