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

2024-04-25 08:48:20 发布

您现在位置: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

如果我在另一个模块中,我可以使用:

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

我能在同一模块中做同样的事情吗

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


Tags: 模块the字符串namefoodefbarsome