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 に答える