0

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)
Özgür
  • 3
  • 1

1 Answers1

8

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 = []
[...]
wRAR
  • 25,009
  • 4
  • 84
  • 97
  • And just for reference, here is a link to a question about the difference between class and instance attributes: http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes – jdi Feb 11 '12 at 16:01