如何获取模块中定义但未导入的所有类? [英] How do you get all classes defined in a module but not imported?
问题描述
我已经看到以下问题,但它并没有让我达到我想要的目的:如何在 Python 中获取当前模块中所有类的列表?
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
?
How can I get only NewClass
, AnotherClass
and YetAnotherClass
?
推荐答案
检查类的 __module__
属性以找出它是在哪个模块中定义的.
Inspect the __module__
attribute of the class to find out which module it was defined in.
这篇关于如何获取模块中定义但未导入的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!