How to refer to an instance of a class using a str

2019-07-19 08:04发布

问题:

I'm a bit inexperienced with python, and I've been searching and searching but can't find a useful answer to this.

I have instances of a class named tool1, tool2, etc.

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'

How do I set current_tool equal to my_string so that current_tool = tool1?

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.

回答1:

Use a dictionary:

tools = {'tool1': ...,
         'tool2': ...}

my_string = 'tool1'
current_tool = tools[my_string]