2013-10-14 25 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的列表是相同的列表。