表示双向可遍历层次结构的最佳方法

jon*_*opf 0 python parent parent-child hierarchy

我需要将一些数据表示为一个层次结构,其中一个对象可以有一个父项和多个子项.我还需要能够以与孩子相同的方式获得孩子的父母.

我试过这个

class Root():
    def __init__(self):
        self.child = Node(self)

class Node():
    def __init__(self, parent):
        self.parent = parent
Run Code Online (Sandbox Code Playgroud)

有没有一种解决这个问题的常用方法

mgi*_*son 7

我认为这基本上Tkinter是这样的:

class Root(object):
    def __init__(self):
        self.children = []

class Node(object):
   def __init__(self,parent):
        self.parent = parent
        parent.children.append(self)
Run Code Online (Sandbox Code Playgroud)

现在,Root通过children属性了解所有孩子,孩子们通过属性了解他们的父母parent.

r = Root()
n = Node(r)
r.children[0] is n  #True
n.parent is r  #True
Run Code Online (Sandbox Code Playgroud)

当然,你也可以通过赋予Node对象一个children属性来使事情变得更有趣- 然后Nodes可以生成更多的Nodes.整齐.

这里有一些缺点(主要是循环引用).如果你想避免这种情况,你可以使用weakref.refs来存储对孩子/父母的引用,但如果有必要,我会将其推迟到另一个问题.