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

0 python recursion inheritance

我正在尝试学习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)
Run Code Online (Sandbox Code Playgroud)

wRA*_*RAR 8

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

您应该删除children = []并创建它__init__:

class Container:
    tag = 'container'

    def __init__(self):
        self.children = []
[...]
Run Code Online (Sandbox Code Playgroud)