2012-02-11 196 views
0

我想学习python,我不知道为什么最后一条语句导致无限递归调用。有人可以解释如何在python中实现嵌套对象的递归打印?

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

因为你不分配self.children,该children场的Container所有实例之间共享。

您应该删除children = []__init__创建它来代替:

class Container: 
    tag = 'container' 

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

Offcourse!非常感谢。 – 2012-02-11 15:59:42

+0

仅供参考,以下是有关类和实例属性之间差异问题的链接:http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes – jdi 2012-02-11 16:01:27