简体   繁体   中英

How to implement recursive printing of nested objects in python?

I am trying to learn python and I have no clue why the last statement results in an infinite recursive call. Can someone explain

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)

Because you do not assign self.children , the children field is shared between all instances of Container .

You should remove children = [] and create it in __init__ instead:

class Container:
    tag = 'container'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM