在python中,将child附加到root.children(list),并将child.children(list)更改?

时间:2012-06-25 10:08:15

标签: python

代码:

class Node:
    def __init__(self, key, children=[]):
        self.key = key
        self.children = children

    def __repr__(self):
        return self.key

执行:

root = Node("root")
child = Node("child")
root.children.append(child)
print child.children
print root.children[0].children

结果:

[child]
[child]

这真的很奇怪,为什么?

Python的版本是2.7.2。

2 个答案:

答案 0 :(得分:5)

你不应该使用可变对象作为参数的默认值(除非你完全知道你在做什么)。有关说明,请参阅this article

改为使用:

class Node:
    def __init__(self, key, children=None):
        self.key = key
        self.children = children if children is not None or []

答案 1 :(得分:0)

class Node:
    def __init__(self, key,children): # don't use children =[] here, it has some side effects, see the example below
        self.key = key
        self.children =children

    def __repr__(self):
        return self.key

root = Node("root",[])
child = Node("child",[])
root.children.append(child)
print root.children
print root.children[0].key

<强>输出:

[child]
child

示例:

def example(lis=[]):
    lis.append(1) #lis persists value
    print(lis)
example()
example()
example()

输出:

[1]
[1, 1]
[1, 1, 1]