Python Composite Desing Pattern - RecursionError: maximum recursion depth exceeded
<p>so i was a bit going trough some design patterns books and i decided to make my own in python (the book is for Java), and i stumbled on this issue which i cannot solve,what am i missing here?</p>

<p>So why do i get here recursion error?</p>

<pre><code>class Component:

    _components = []

    def __init__(self, value):
        self.value = value

    def add(self, *components):
        self._components.extend(components)

    def remove(self, *components):
        self._components = list(set(self._components).difference(set(components)))

    def get_components(self):
        return self._components

    def __repr__(self):
        return "Component value: {}".format(self.value)


class ComputerComponent(Component):

    def turn_on(self):
        self.on = True
        for component in self.get_components( ):
            component.turn_on( )
        print("{} turned on".format(self.value))



class Computer(ComputerComponent):
    pass

class LCDScreen(ComputerComponent):
    pass

class Mouse(ComputerComponent):
    pass

class Keyboard(ComputerComponent):
    pass

computer = Computer("computer")
lcd_screen = LCDScreen("lcd_screen")
mouse = Mouse("mouse")
keyboard = Keyboard("keyboard")

computer.add(lcd_screen,mouse,keyboard)

computer.turn_on( )
</code></pre>

<p><code>_components</code> should be an instance variable, not a class variable. As it is, adding the components to the computer adds them to <em>all</em> the other components. That is, every component is a component of every other component, which results in an infinite loop.</p>

<pre><code>class Component:

    def __init__(self, value):
        self.value = value
        self._components = []

    def add(self, *components):
        self._components.extend(components)

    def remove(self, *components):
        self._components = list(set(self._components).difference(set(components)))

    def get_components(self):
        return self._components

    def __repr__(self):
        return "Component value: {}".format(self.value)
</code></pre>

python recursion composite