2

代码:

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。

4

2 回答 2

5

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

而是使用:

class Node:
    def __init__(self, key, children=None):
        self.key = key
        self.children = children if children is not None or []
于 2012-06-25T10:17:06.570 回答
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]
于 2012-06-25T10:19:19.840 回答