如何使用字符串引用类的实例? [英] How to refer to an instance of a class using a string?
问题描述
我对python有点经验,我一直在搜索和搜索,但是找不到一个有用的答案。
I'm a bit inexperienced with python, and I've been searching and searching but can't find a useful answer to this.
我有实例一个名为tool1,tool2等的类。
I have instances of a class named tool1, tool2, etc.
如何获取由用户输入定义的字符串,并使用它来设置一个变量(current_tool)类的实例?例如:
How do I take a string that is defined by user input and use it to set a variable (current_tool) equal to one of the instances of the class? For example:
tool1 = ...
tool2 = ...
current_tool = 0
my_string = 'tool1'
如何设置current_tool等于到my_string,以便 current_tool = tool1
?
我本质上是在寻找如何'该字符串使得该字符串只是一段代码。任何使用exec或eval的尝试都没有成功。
I'm essentially looking for how to 'remove' the quotes from the string so that the string is just a piece of code. Any attempts I've made using exec or eval haven't worked.
任何帮助将不胜感激。谢谢。
Any help would be appreciated. Thank you.
推荐答案
使用字典:
tools = {'tool1': ...,
'tool2': ...}
my_string = 'tool1'
current_tool = tools[my_string]
这篇关于如何使用字符串引用类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!