给定一个名为
ParentClass
的基类,我如何找到它的所有叶子类?例如,如果我有:
class ParentClass:
pass
class SubClass1(ParentClass):
pass
class SubClass2(ParentClass):
pass
class SubClass3(ParentClass):
pass
class SubClass4(SubClass2):
pass
class SubClass5(SubClass2):
pass
class SubClass6(SubClass2, SubClass3):
pass
我想要一个包含
[SubClass1, SubClass4, SubClass5, SubClass6]
的列表,而不是 SubClass2
或 SubClass3
,因为它们不是继承层次结构中的叶子。
此函数从父类开始,迭代其子类,将唯一的叶子类附加到列表中。
def leaf_subclasses(parent_class):
leaves = []
subclasses = [parent_class]
while subclasses:
next_subclasses = []
for cls in subclasses:
if cls.__subclasses__():
next_subclasses.extend(cls.__subclasses__())
elif cls not in leaves:
leaves.append(cls)
subclasses = next_subclasses
return leaves
print(leaf_subclasses(ParentClass))