Reputation: 175
Suppose I have this classes:
class a(object):
pass
class b(a):
pass
class c(b):
pass
class d(c):
pass
class e(b):
pass
I want a function that will do somthing like:
>>>get_ inheritance_tree(a)
>>>...b
>>>......c
>>>.........d
>>>......e
Upvotes: 8
Views: 4364
Reputation: 895
If you don't care about graphical presentation and need a list of children, then a recursive function could be used to prepare the list:
def get_all_subclasses(class_to_analize):
all_subclasses = []
for subclass in class_to_analize.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses
print(get_all_subclasses(a))
The output will be:
[<class '__main__.b'>, <class '__main__.c'>, <class '__main__.d'>, <class '__main__.e'>]
Upvotes: 0
Reputation: 3883
Here is a more beautiful version of the Hugo's answer:
def class_tree(cls):
return { cls.__name__: [class_tree(sub_class) for sub_class in cls.__subclasses__()] }
def print_tree(tree, indent=4, current_ind=0):
for k, v in tree.items():
if current_ind:
before_dashes = current_ind - indent
print(' ' * before_dashes + '└' + '-'*(indent-1) + k)
else:
print(k)
for sub_tree in v:
print_tree(sub_tree, indent=indent, current_ind=current_ind + indent)
Result:
>>> ct = class_tree(a)
>>> print_tree(ct, indent=4)
a
└---b
└---c
└---d
└---e
Upvotes: 2
Reputation: 1979
If you do not need visualisation but do need a tree, there is a simple way to do it if you represent the tree by a nested list of branch [object, [children]]
and leaves [object, [[]]]
.
Then, by defining the recursive function:
def classTree(cls): # return all subclasses in form of a tree (nested list)
return [cls, [[b for c in cls.__subclasses__() for b in classTree(c)]]]
You can get the inheritance tree:
>>> classTree(A)
[<class 'A'>, [[<class 'B'>, [[<class 'C'>, [[<class 'D'>, [[]]]], <class 'E'>, [[]]]]]]]
Upvotes: 1