在python中将节点插入树中

时间:2013-10-12 02:49:24

标签: python arrays recursion tree append

我正在尝试编写一个节点类来创建树结构。似乎有 当我尝试使用方法“addChild”将子节点添加到根节点时,会出现一些问题,因为子节点似乎在其子节点列表中有自己的节点。我无法弄清楚原因,所以任何帮助都表示赞赏。

class node(object):
    def __init__(self, name, x, y, children = []):
        self.name = name
        self.children = children
        self.x = x
        self.y = y

    def addChild(self): 
        b=node('b', 5, 5)
        self.children.append(b)
        return

root=node('a',0.,0.)
print root.children 

root.addChild() 

print root.children
print root.children[0].children

收率:

[<__main__.node object at 0x7faca9f93e50>]
[<__main__.node object at 0x7faca9f93e50>]

而第二个“print”行应返回一个空数组。

1 个答案:

答案 0 :(得分:4)

默认参数值children = []将单个列表对象分配给__init__函数,然后在每次调用所有子项时使用该函数。 This is a common mistake。而是在children函数本身中创建__init__

class node(object):
    def __init__(self, name, x, y, children=None):
        self.name = name
        self.children = [] if children is None else children
        self.x = x
        self.y = y
 # ...