Python:找到从这个继承的所有类? [英] Python: find all classes which inherit from this one?

查看:56
本文介绍了Python:找到从这个继承的所有类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中是否有任何方法可以查询从特定类继承的类的命名空间?给定一个类小部件我希望能够调用类似的继承者(小部件)来获取一个列表所有我不同类型的小部件。

Is there any way in python to query a namespace for classes which inherit from a particular class? Given a class widget I'd like to be able to call something like inheritors(widget) to get a list of all my different kinds of widget.

推荐答案

你想使用小部件.__子类__()获取所有子类的列表。它只查找直接子类,但如果你想要所有这些,你将不得不做更多的工作:

You want to use Widget.__subclasses__() to get a list of all the subclasses. It only looks for direct subclasses though so if you want all of them you'll have to do a bit more work:

def inheritors(klass):
    subclasses = set()
    work = [klass]
    while work:
        parent = work.pop()
        for child in parent.__subclasses__():
            if child not in subclasses:
                subclasses.add(child)
                work.append(child)
    return subclasses

NB如果您使用的是Python 2.x,则仅适用于新式类。

N.B. If you are using Python 2.x this only works for new-style classes.

这篇关于Python:找到从这个继承的所有类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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