generate a dependency tree of the inheritance hierarchy
i am trying to write a recursive algorithm to generate a dependency tree of the inheritance hierarchy of a class. Below is my sample code. The problem i am getting is when we the elements in the bases list are more than one, only the 1st element of the list and its parent classes are printed.
def get_bases(klass):
bases = getattr(klass, '__bases__')
if len(bases) == 0:
return None
else:
for开发者_如何学编程 item in bases:
print item
return get_bases(item)
I also would like to generate some kind of graph showing the inheritance hierarchy. Kindly help!
The problem is here:
for item in bases:
print item
return get_bases(item)
You recurse into the item, and then immediately return without continuing through the for loop. You can replace with something like:
for item in bases:
print item
get_bases(item)
or you could perhaps build up a tree structure instead for printing later (pprint_node shows one possible implementation):
class Node(object):
def __init__(self, item, children):
self.item = item
self.children = children
def get_class_tree(klass):
bases = getattr(klass, '__bases__')
return Node(klass, [get_class_tree(item) for item in bases])
def pprint_node(node, level=0):
print (" "*level) + str(node.item)
for child in node.children:
pprint_node(child, level+1)
精彩评论