Last active
September 15, 2020 17:59
-
-
Save rmariano/7e0d778045db60fd3f31 to your computer and use it in GitHub Desktop.
LeaveClasses.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Top(object): | |
pass | |
class A(Top): pass | |
class B(Top): pass | |
class A1(A): pass | |
class A2(A): pass | |
class B1(B): pass | |
class B2(B): pass | |
class get_leave_classes(object): | |
"""Iterator that yields a subclass on each iteration | |
Return only bottom-level classes, the leaves of the hierarchy tree | |
""" | |
def __init__(self, top_cls): | |
self.to_explore = top_cls.__subclasses__() | |
def __iter__(self): | |
return self | |
def __next__(self): | |
while self.to_explore: | |
leaf = self.to_explore.pop(0) | |
if not leaf.__subclasses__(): | |
return leaf | |
self.to_explore.extend(leaf.__subclasses__()) | |
raise StopIteration() | |
for class_ in get_leave_classes(Top): | |
print(class_.__name__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment