我对 python 有点缺乏经验,我一直在搜索和搜索但找不到有用的答案。
我有一个名为 tool1、tool2 等的类的实例。
我如何获取由用户输入定义的字符串并使用它来设置一个变量 (current_tool) 等于该类的一个实例?例如:
tool1 = ...
tool2 = ...
current_tool = 0
my_string = 'tool1'
如何设置 current_tool 等于 my_string 以便 current_tool = tool1?
我实际上是在寻找如何从字符串中“删除”引号,以便该字符串只是一段代码。我使用 exec 或 eval 所做的任何尝试都没有奏效。
如有任何帮助,我们将不胜感激。谢谢。
请您参考如下方法:
使用字典:
tools = {'tool1': ...,
'tool2': ...}
my_string = 'tool1'
current_tool = tools[my_string]
