How do I convert a python string that I'm getting from the user to a function name
本问题已经有最佳答案,请猛点这里访问。
我从用户那里接收一个输入,并将其存储在一个名为videotype的变量中。
我的问题是,如何将用户提供给videotype的字符串转换成一个函数名,这个函数名是我和其他许多python中的函数名一起定义的?
前任。用户输入:"get_mpeg()"存储在视频类型中
我将使用这个输入作为函数名。
我要编一本字典。字典的键是用户输入,值是函数。像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def compliment(): print("You look nice today.") def insult(): print("You look awful today.") def default_function(): print("Sorry, I don't know what you mean") functions = { "compliment": compliment, "nice": compliment, # aliased command "insult": insult, "mean": insult, } videoType = input("What shall I do?") functions.get(videoType, default_function)() |
无论您做什么,都不要直接将用户的输入转换为代码。考虑一下如果用户输入
您可以制作一个字典,将函数名映射到相应的函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def foo(): print('foo called') def bar(): print('bar called') exposed_functions = { 'foo': foo, 'bar': bar } if __name__ == '__main__': user_input = 'foo' # Pretend the user passed you this string function = exposed_functions[user_input] function() |
这种方法似乎是多余的,但您可能不希望用户传递像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import functools exposed_functions = {} def expose(*names): def decorator(function): for name in (names or [function.__name__]): exposed_functions[name] = function return function return decorator @expose() # `name` is automatically extracted out of the function def foo(): print('foo called') @expose('bar', 'baz') # binds to both `bar` and `baz` def bar(): print('bar called') if __name__ == '__main__': user_input = 'baz' # Pretend the user passed you this string function = exposed_functions[user_input] function() |
您还可以使用
1 2 3 4 5 6 | def hello(): print('hello') videoType = input("Name a function") globals()[videoType)() |