代碼:在python中,將子項添加到root.children(list)和child.children(list)已更改?
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。
作爲默認值的可變對象! 'def __init __(self,key,children = None):\\ children = children或[]' – astynax
這是python的一個bug? – LeoDT
不,看到這個問題:http://stackoverflow.com/q/1132941/623518 – Chris