Python堆栈损坏?

2024-05-20 14:17:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python比较陌生(但不熟悉编程),我无法解释以下行为。一个对象(“child”)中的一个变量(在我的示例中是“children”)似乎被另一个完全不同的对象(“node”)中的变量值覆盖。为了提供一些上下文,我尝试创建一个简单的节点类,以便在树结构中使用。节点有子节点和父节点(所有其他节点)。在

我不明白为什么孩子。孩子获取与相同的值节点.子项. 他们是否引用了相同的数据?为什么?代码和输出如下:

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

输出:

^{pr2}$

如你所见,两者节点.子项以及孩子。孩子即使我只更新了节点.子项. 谢谢你的帮助!在


Tags: 对象posselfnodechild节点def孩子
2条回答

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 = []
    ...

相关问题 更多 >