【问题标题】:How to refer to an instance of a class using a string?如何使用字符串引用类的实例?
【发布时间】:2013-07-28 19:08:56
【问题描述】:

我对python有点缺乏经验,一直在搜索和搜索但找不到有用的答案。

我有一个名为 tool1、tool2 等的类的实例。

如何获取由用户输入定义的字符串并使用它来设置变量 (current_tool) 等于类的实例之一?例如:

tool1 = ...
tool2 = ...

current_tool = 0

my_string = 'tool1'

如何将 current_tool 设置为等于 my_string 以便 current_tool = tool1

我实际上是在寻找如何从字符串中“删除”引号,以便字符串只是一段代码。我使用 exec 或 eval 所做的任何尝试都没有奏效。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: python string class instance


    【解决方案1】:

    使用字典:

    tools = {'tool1': ...,
             'tool2': ...}
    
    my_string = 'tool1'
    current_tool = tools[my_string]
    

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2011-06-02
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多