如何获得模块中定义但未导入的所有类? [英] How do you get all classes defined in a module but not imported?

查看:80
本文介绍了如何获得模块中定义但未导入的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过以下问题,但并不能完全解决我想要的问题:

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),它将返回MyBaseClassSomeOtherClass,除了此模块中定义的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.

如何仅获取NewClassAnotherClassYetAnotherClass?

推荐答案

检查类的__module__属性以找出其定义在哪个模块中.

Inspect the __module__ attribute of the class to find out which module it was defined in.

这篇关于如何获得模块中定义但未导入的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆