从同一模块中的类名字符串获取Python类对象

从同一模块中的类名字符串获取Python类对象,python,Python,我有一节课 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类 如果

我有一节课

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")
我能在同一模块中做同样的事情吗

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

globals()[class_name]
请注意,如果这不是严格必需的,您可能希望重构代码以不使用它。

import sys
getattr(sys.modules[__name__], "Foo")

# or 

globals()['Foo']

是的,使用映射dict可能是正确的方法…谢谢。我最终进行了重构,因为我不想使用
globals
或使用映射命令。我接受了这个答案,因为它涵盖了
sys
globals
方法。
import sys

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