I don't understand python's behavior, I've got many the same errors:
File "./start.py", line 20, in print2
item.print2()
RuntimeError: maximum recursion depth exceeded
My code is the following:
#!/usr/bin/python
class Component:
def print2(self):
pass
class Composite(Component):
items = []
name = 'composite'
def __init__(self, name):
self.name = name
def add(self, item):
self.items.append(item)
def print2(self):
if self.items:
for item in self.items:
item.print2()
else:
print self.name
class Leaf(Component):
name = 'leaf'
def __init__(self, name):
self.name = name
def print2(self):
print self.name
category = Composite('category1')
leaf = Composite('leaf1')
category.add(leaf)
leaf = Leaf('leaf2')
category.add(leaf)
category.print2()
When I add self.items = [] in the constructor ( __init__ ), it works fine. Could you explain the behavior?
items... that is a class variable, i.e. "static"__init__are static elements belonging to the class, elements inside of__init__are members of the object, they do not belong to the class. Which means that every time you callprint2(), regardless of the object,self.itemscontains 2 Composites.