生成继承层次结构的依赖树

发布于 2024-10-22 14:25:45 字数 329 浏览 1 评论 0原文

我正在尝试编写一个递归算法来生成类的继承层次结构的依赖树。下面是我的示例代码。我遇到的问题是,当基列表中的元素超过一个时,仅打印列表的第一个元素及其父类。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴随着你 2024-10-29 14:25:45

问题就在这里:

for item in bases:
    print item
    return get_bases(item)

您递归到该项目,然后立即返回而不继续执行for循环。您可以替换为以下内容:

for item in bases:
    print item
    get_bases(item)

或者您可以构建一个树结构,而不是稍后打印(pprint_node 显示了一种可能的实现):

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文