递归编辑成员变量:所有实例都具有相同的值

recursively editing member variable: All instances have same value

我想创建一个由 TreeNode objects 组成的树数据结构。根是一个 TreeNode。每个 TreeNode 都有一个 parent TreeNode 和一个 children TreeNodes 列表。 树是递归建立的。我简化了代码以使示例不太困难。函数 get_list_of_values_from_somewhere 工作正常。当 TreeNode 没有 child_values 且 get_list_of_values_from_somewhere returns 为空列表时,递归结束。效果很好。

每个 TreeNode 的 children 成员不正确。该脚本收集列表中的所有 TreeNodes (node_list)。在那里我可以检查每个 TreeNode 都有一个 parent 节点并且这个 parent 节点是正确的。

但出于某种原因,它们都有相同的 children 列表。我不明白为什么。其他一切都是正确的。递归有效,正确创建了 TreeNodes,它们的 parent 是正确的。为什么他们的 children 列表没有正确填写,您将如何编辑实例的 memver 变量 创建实例之后?

class Tree(object):

    def __init__(self, root_value):
        print ("Creating tree")
        self.root = self.createTree(root_value)
        self.node_list = []

    def createTree(self, value, parent=None):
        node = TreeNode(value, parent)

        children_values = get_list_of_values_from_somewhere()
        for child_value in children_values:
            child_node = self.createTree(child_value, node)
            self.node_list.append(child_node)

            node.children.append(child_node)
            # I also tried alternatives:
            #node.insertChildren(self.createTree(child_value, node))
            #node.insertChild(child_node)

        return node


class TreeNode(object):

    def __init__(self, value, parent=None, children=[]):

        self.value = value
        self.parent = parent
        self.children = children

    def insertChildren(self, children=[]):
        self.children += children

    def insertChild(self, child):
        self.children.append(child)


if __name__ == '__main__':
    tree = Tree(1)

    #tree.node_list contains a list of nodes, their parent is correct
    #tree.root.children contains all children
    #tree.node_list[x] contains the same children - although many of them should not even have a single child. Otherwise the recursion would not end.

对此要非常非常谨慎:

def __init__(self, value, parent=None, children=[]):

还有这个:

def insertChildren(self, children=[]):

初始值 -- [] 创建的列表对象 -- 是共享的单个对象。广泛。

您正在广泛使用这个单一的、共享的、默认的列表对象。

您可能想改用它。

def __init__( self, value, parent= None, children= None ):
    if children is None: children= []

此技术将创建一个新的空列表对象。没有分享。