生成继承层次结构的依赖树
我正在尝试编写一个递归算法来生成类的继承层次结构的依赖树。下面是我的示例代码。我遇到的问题是,当基列表中的元素超过一个时,仅打印列表的第一个元素及其父类。
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 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题就在这里:
您递归到该项目,然后立即返回而不继续执行for循环。您可以替换为以下内容:
或者您可以构建一个树结构,而不是稍后打印(pprint_node 显示了一种可能的实现):
The problem is here:
You recurse into the item, and then immediately return without continuing through the for loop. You can replace with something like:
or you could perhaps build up a tree structure instead for printing later (pprint_node shows one possible implementation):