从同一模块中的类名字符串中获取 Python 类对象 [英] Get Python class object from class name string in the same module
本文介绍了从同一模块中的类名字符串中获取 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
类.
I want to be able to access the Foo
class using the string "Foo".
如果我在另一个模块中,我可以使用:
I can do this if I'm in another module by using:
from project import foo_module
foo_class = getattr(foo_module, "Foo")
我可以在同一个模块中做同样的事情吗?
Can I do the same sort of thing in the same module?
IRC 中的人建议我使用映射字典将字符串类名映射到类,但如果有更简单的方法,我不想这样做.
The guys in IRC suggested I use a mapping dict that maps string class names to the classes, but I don't want to do that if there's an easier way.
推荐答案
import sys
getattr(sys.modules[__name__], "Foo")
# or
globals()['Foo']
这篇关于从同一模块中的类名字符串中获取 Python 类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文