【问题标题】:How to get class object from class name string in the same module?如何从同一模块中的类名字符串中获取类对象?
【发布时间】:2013-07-31 08:46:27
【问题描述】:

我有课

class Foo():
    def some_method():
        pass

还有另一个类在同一个模块中

class Bar():
    def some_other_method():
        class_name = "Foo"
        # Can I access the class Foo above using the string "Foo"?

我希望能够使用字符串“Foo”访问Foo 类。

如果我在另一个模块中,我可以这样做:

from project import foo_module
foo_class = getattr(foo_module, "Foo")

我可以在同一个模块中做同样的事情吗?

IRC 中的人建议我使用映射字典,将字符串类名映射到类,但如果有更简单的方法,我不想这样做。

【问题讨论】:

  • 是的,使用映射字典可能是正确的方法......
  • 谢谢。我最终重构了,因为我不想使用 globals 或使用映射字典。

标签: python


【解决方案1】:

You can do it with help of the sys module:

import sys

def str2Class(str):
    return getattr(sys.modules[__name__], str)

【讨论】:

    【解决方案2】:
    import sys
    getattr(sys.modules[__name__], "Foo")
    
    # or 
    
    globals()['Foo']
    

    【讨论】:

    • 接受了这个答案,因为它涵盖了sysglobals 方法。
    【解决方案3】:
    globals()[class_name]
    

    请注意,如果这不是绝对必要的,您可能需要重构代码以不使用它。

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多