【问题标题】:inserting a node into a tree in python在python中将节点插入树中
【发布时间】:2013-10-20 05:31:52
【问题描述】:

我正在尝试编写一个节点类来创建树结构。好像有 当我尝试使用“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>]

而第二个“打印”行应该返回一个空数组。

【问题讨论】:

标签: python arrays recursion tree append


【解决方案1】:

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

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
 # ...

【讨论】:

    猜你喜欢
    • 2021-09-03
    • 2020-09-29
    • 2012-10-03
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多