2013-10-14 60 views
2
class Tree: 
    def __init__(self, label, children = []): 
     self.label = label 
     self.children = children 

t1 = Tree("START") 
t2 = Tree("END") 
t1.children.append(t2) 

print t2.children 
[<__main__.Tree instance at 0x005421C0>] 

爲什麼不是t2.children爲空?在構造函數中實例化列表的問題

+0

看看上面的鏈接:每個人都被這個問題最終會感到驚訝。對於Python的方式建議,以解決它,看看http://stackoverflow.com/questions/366422/what-is-the-pythonic-way-to-avoid-default-parameters-that-are-empty-lists –

回答

0

的問題是,默認值只執行一次 - 當DEF語句excuted。 因此,所有實例對象的孩子被分配相同的列表。

總之,t1t2的列表是相同的列表。

相關問題