Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3:使str对象可调用_Python_String_Object_Callable - Fatal编程技术网

Python 3:使str对象可调用

Python 3:使str对象可调用,python,string,object,callable,Python,String,Object,Callable,我有一个Python程序,它接受用户输入。我将用户输入存储为一个名为“userInput”的字符串变量。我希望能够调用用户输入的字符串 userInput = input("Enter a command: ") userInput() 由此,我得到了一个错误:TypeError:'str'对象不可调用 目前,我的计划是这样做的: userInput = input("Enter a command: ") if userInput == 'example_command': exam

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

userInput = input("Enter a command: ")
userInput()
由此,我得到了一个错误:TypeError:'str'对象不可调用

目前,我的计划是这样做的:

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

def example_command():
     print('Hello World!')
显然,这不是处理大量命令的非常有效的方法。
我想使str obj可调用-无论如何都可以这样做?

更好的方法可能是使用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.")
本质上,您提供了literal命令和您可能想要运行的函数之间的映射

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

def command1():
    pass

def command2():
    pass

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

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

我认为您需要的是eval('string')。请确保您对该字符串进行了大量检查,否则您将遇到一些重大的安全问题。您还必须在输入字符串的末尾添加“()”。@Evan即使进行了大量检查,对用户输入运行eval也可能不是个好主意。您要做的检查是“此字符串是否为已批准的集合之一”,此时您最好执行dict查找。@Evan只是好奇,eval()的作用是什么&为什么它会导致安全问题?它尝试运行字符串。如果一个黑客想进入你的系统,这会让它变得非常容易。他们只需要知道调用什么函数和变量。然后他们就继续快乐的生活。例如,如果您有一个带有变量“size”的链表,我想exec也可以调用eval,“my_list.size=0”并更改大小。谢谢@Evan,我现在明白了。谢谢!你比我快了8秒。干得好,先生,干得好!你们太聪明了:)谢谢你们!帮了我很多忙!;)