如何获得模块中定义但未导入的所有类? [英] How do you get all classes defined in a module but not imported?
问题描述
I've already seen the following question but it doesn't quite get me where I want: How can I get a list of all classes within current module in Python?
特别是,我不希望导入的类,例如如果我有以下模块:
In particular, I do not want classes that are imported, e.g. if I had the following module:
from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass
class NewClass(MyBaseClass):
pass
class AnotherClass(MyBaseClass):
pass
class YetAnotherClass(MyBaseClass):
pass
如果我像链接问题中所接受的答案一样使用clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
,它将返回MyBaseClass
和SomeOtherClass
,除了此模块中定义的3之外.
If I use clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
like the accepted answer in the linked question suggests, it would return MyBaseClass
and SomeOtherClass
in addition to the 3 defined in this module.
如何仅获取NewClass
,AnotherClass
和YetAnotherClass
?
推荐答案
检查类的__module__
属性以找出其定义在哪个模块中.
Inspect the __module__
attribute of the class to find out which module it was defined in.
这篇关于如何获得模块中定义但未导入的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!