2013-10-14 7 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

위의 링크를 확인하십시오. 결국 모든 사람이이 문제에 놀랐습니다. 해결할 Pythonic 방법에 대한 제안은 http://stackoverflow.com/questions/366422/what-is-the-pythonic-way-to-avoid-default-parameters-that-are-empty-lists를 확인하십시오. –

답변

0

def 문이 실행될 때 기본값이 한 번만 실행되는 것이 문제입니다. 따라서 모든 인스턴스 객체의 자식에는 동일한 목록이 할당됩니다.

요약하면 t1t2의 목록은 같은 목록입니다.

관련 문제