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

Leo*_*oDT 1 python

码:

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

    def __repr__(self):
        return self.key
Run Code Online (Sandbox Code Playgroud)

执行:

root = Node("root")
child = Node("child")
root.children.append(child)
print child.children
print root.children[0].children
Run Code Online (Sandbox Code Playgroud)

结果:

[child]
[child]
Run Code Online (Sandbox Code Playgroud)

这真的很奇怪,为什么?

Python的版本是2.7.2.

Mar*_*mro 5

您不应该使用可变对象作为参数的默认值(除非您确切知道自己在做什么).请参阅此文章以获取解释.

而是使用:

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