如何在Python中找到给定类的所有子类?

问题:

我需要一种工作方法来获取在Python中从基类继承的所有类。

回答:

新式类(即从object分类,在Python 3中是默认的)具有返回子类的__subclasses__方法:

class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass

以下是子类的名称:

print([cls.__name__ for cls in vars()['Foo'].__subclasses__()])
# ['Bar', 'Baz']

这是子类本身:

print(vars()['Foo'].__subclasses__())
# [<class '__main__.Bar'>, <class '__main__.Baz'>]

确认子类确实列出Foo作为它们的基础:

for cls in vars()['Foo'].__subclasses__():
    print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>

注意,如果你想要子类,你必须递归:

def all_subclasses(cls):
    return cls.__subclasses__() + [g for s in cls.__subclasses__()
                                   for g in all_subclasses(s)]

print(all_subclasses(vars()['Foo']))
# [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: How can I find all subclasses of a given class in Python?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

12 − 7 =