jus*_*mer 7 python string object callable
我有一个Python程序,需要用户输入.我存储用户输入一个名为"userInput"的字符串变量.我希望能够调用用户输入的字符串...
userInput = input("Enter a command: ")
userInput()
Run Code Online (Sandbox Code Playgroud)
从这里,我得到错误:TypeError:'str'对象不可调用
目前,我有程序做这样的事情:
userInput = input("Enter a command: ")
if userInput == 'example_command':
example_command()
def example_command():
print('Hello World!')
Run Code Online (Sandbox Code Playgroud)
显然,这不是处理大量命令的非常有效的方法.我想让str obj可以调用 - 无论如何这样做?
Mic*_*x2a 19
更好的方法可能是使用dict:
def command1():
pass
def command2():
pass
commands = {
'command1': command1,
'command2': command2
}
user_input = input("Enter a command: ")
if user_input in commands:
func = commands[user_input]
func()
# You could also shorten this to:
# commands[user_input]()
else:
print("Command not found.")
Run Code Online (Sandbox Code Playgroud)
实际上,您在文字命令和您可能想要运行的函数之间提供映射.
如果输入太多,您还可以使用local关键字,这将返回当前范围内当前定义的每个函数,变量等的字典:
def command1():
pass
def command2():
pass
user_input = input("Enter a command: ")
if user_input in locals():
func = locals()[user_input]
func()
Run Code Online (Sandbox Code Playgroud)
但这并不完全安全,因为恶意用户可以输入与变量名称相同的命令,或者您不希望它们运行的某些功能,并最终导致代码崩溃.