gpt4 book ai didi

python 3 : Making a str object callable

转载 作者:太空狗 更新时间:2023-10-29 21:18:30 25 4
gpt4 key购买 nike

我有一个接受用户输入的 Python 程序。我将用户输入存储在一个名为“userInput”的字符串变量中。我希望能够调用用户输入的字符串...

userInput = input("Enter a command: ")
userInput()

由此,我得到错误:TypeError: 'str' object is not callable

目前,我的程序正在做这样的事情:

userInput = input("Enter a command: ")
if userInput == 'example_command':
example_command()

def example_command():
print('Hello World!')

显然,这不是处理大量命令的非常有效的方法。我想让 str obj 可调用 - 无论如何都要这样做?

最佳答案

更好的方法可能是使用字典:

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.")

本质上,您提供了文字命令与您可能想要运行的函数之间的映射。

如果输入太多,您还可以使用 local 关键字,它将返回当前范围内当前定义的每个函数、变量等的字典:

def command1():
pass

def command2():
pass

user_input = input("Enter a command: ")
if user_input in locals():
func = locals()[user_input]
func()

但这并不完全安全,因为恶意用户可能会输入与变量名称相同的命令,或者您不希望它们运行的​​某些函数,并最终导致代码崩溃。

关于 python 3 : Making a str object callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23177308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com