如何在python中实现嵌套对象的递归打印?

如何在python中实现嵌套对象的递归打印?,python,inheritance,recursion,Python,Inheritance,Recursion,我正在尝试学习python,我不知道为什么最后一条语句会导致无限递归调用。有人能解释一下吗 class Container: tag = 'container' children = [] def add(self,child): self.children.append(child) def __str__(self): result = '<'+self.tag+'>' for child in

我正在尝试学习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)
类容器:
标记='container'
儿童=[]
def添加(自身、子项):
self.children.append(子级)
定义(自我):
结果=“”
对于在self.children中的children:
结果+=str(子项)
结果+=“”
返回结果
类别分包商(集装箱):
标记='sub'
c=容器()
d=分包商()
c、 加(d)
印刷品(c)

因为您没有分配
self.children
,所以
children
字段在
容器的所有实例之间共享

您应该删除
子项=[]
并在
\uuuuu init\uuuu
中创建它:

class Container:
    tag = 'container'

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

仅供参考,这里有一个链接,指向一个关于类和实例属性之间差异的问题: