Python堆栈损坏



我对python比较陌生(但不是编程),我无法解释以下行为。似乎来自一个对象("child")的变量(在我的示例中是列表"children")正在被完全不同对象("node")中该变量的值覆盖。为了给出一些上下文,我尝试创建一个简单的Node类,用于树形结构。该节点有子节点和父节点(所有其他节点)。

我不知道为什么孩子。Children获得与node.children相同的值。它们是否引用了相同的数据?为什么?代码和输出如下:

class Node:
    children = []
    parent = 0
    visited = 0
    cost = 0
    position = (0, 0)
    leaf = 0
    def __init__(self, parent, pos):
        self.parent = parent
        self.position = pos
    def addChild(self, node):
        self.children += [node]
node = Node(0, (0,0))
child = Node(node, (3,2))
node.addChild(child)
print "node: ",
print node
print "node.childen: ",
print node.children
print "child: ",
print child
print "child.children",
print child.children
输出:

node:  <__main__.Node instance at 0x414b20>
node.childen:  [<__main__.Node instance at 0x414b48>]
child:  <__main__.Node instance at 0x414b48>
child.children [<__main__.Node instance at 0x414b48>]

可以看到,两个节点。孩子和孩子。children具有相同的值(包含child的列表),即使我只更新了node.children。谢谢你的帮助!

children变量被声明为类级变量,因此它在Node的所有实例之间共享。你需要通过在初始化器中设置它来声明它是一个实例变量。

class Node:
    #children = [] # not here...
    parent = 0     # might want to rethink where you initialize these
    visited = 0
    cost = 0
    position = (0, 0)
    leaf = 0
    def __init__(self, parent, pos):
        self.parent = parent
        self.position = pos
        self.children = [] # ...but here
    def addChild(self, node):
        self.children += [node]

你已经让'children'成为一个类属性,这意味着它在该类的所有对象之间共享。

在类的init方法中初始化它。

def __init__(self):
    self.children = []
    ...

最新更新