2012-02-11 3 views
0

파이썬을 배우려고하는데 마지막 문이 무한 재귀 호출을 초래하는 이유를 모르겠습니다. 당신이 self.children을 할당하지 않기 때문에 누군가가파이썬에서 중첩 된 객체를 재귀 적으로 인쇄하는 방법은 무엇입니까?

class Container: 
    tag = 'container' 
    children = [] 

    def add(self,child): 
     self.children.append(child) 

    def __str__(self): 
     result = '<'+self.tag+'>' 
     for child in self.children: 
      result += str(child) 
     result += '<'+self.tag+'/>' 
     return result 

class SubContainer(Container): 
    tag = 'sub' 

c = Container() 
d = SubContainer() 
c.add(d) 
print(c) 

답변

8

를 설명 할 수는 children 필드 Container의 모든 인스턴스간에 공유됩니다.

당신은 children = []를 제거하고 대신 __init__에를 만들어야합니다

class Container: 
    tag = 'container' 

    def __init__(self): 
     self.children = [] 
[...] 
+0

Offcourse! 고마워. –

+0

참고로 클래스 및 인스턴스 속성의 차이점에 대한 질문 링크는 다음과 같습니다. http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes – jdi

관련 문제