代码之家  ›  专栏  ›  技术社区  ›  David Chouinard

Tree实现中的奇怪引用行为[重复]

  •  0
  • David Chouinard  · 技术社区  · 12 年前

    我被一个更大的系统中的一个错误弄得不知所措。考虑这个类(每个节点都维护一个指向其父节点的指针及其子节点的列表):

    class Node:
        children = []
    
        def __init__(self, parent):
            self.contents = dict()
            self.parent = parent
    
            if parent is not None:
                print self.children
                print parent == self
                parent.children.append(self)
                print self.children
    

    运行此:

    foo1 = Node(None)
    foo2 = Node(foo1)
    

    神秘地返回:

    []
    False
    [<__main__.Node instance at 0x10051f128>]
    

    这有什么意义?为什么第二个节点的子节点不为空?也许我错过了对Python如何传递引用这一概念的基本理解。

    1 回复  |  直到 12 年前
        1
  •  3
  •   YXD    12 年前

    您已经定义 children 作为类变量。这是班上所有成员共享的。将声明移入 __init__ 并将其更改为 self.children = [] 你就会得到你期望的结果。