Python栈损坏?

4 投票
2 回答
539 浏览
提问于 2025-04-17 08:58

我对Python还算比较新(但对编程不陌生),有些行为我无法解释。看起来在我的例子中,一个对象(“child”)里的变量(列表“children”)被另一个完全不同的对象(“node”)里的同名变量的值覆盖了。为了给你一些背景,我正在尝试创建一个简单的节点类,用于树结构。这个节点有子节点和父节点(其他所有节点)。

我搞不明白为什么child.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>]

正如你所看到的,node.children和child.children的值都是相同的(一个包含child的列表),尽管我只更新了node.children。感谢任何帮助!

2 个回答

2

你把'children'设置成了一个类属性,这就意味着这个属性在这个类的所有对象之间是共享的。

相反,应该在类的init方法中初始化它。

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

这个 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]

撰写回答