Python Composite Desing Pattern - RecursionError:超出最大递归深度

时间:2016-10-08 22:27:42

标签: python recursion composite

所以我有点想通过一些设计模式的书籍,我决定在python中创建自己的书(这本书是针对Java的),我偶然发现了这个我无法解决的问题,我在这里缺少什么?

那么为什么我会在这里得到递归错误?

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( )

1 个答案:

答案 0 :(得分:2)

if(!document.getElementsByClassName) { document.getElementsByClassName = function(className) { return this.querySelectorAll("." + className); }; Element.prototype.getElementsByClassName = document.getElementsByClassName; } 应该是实例变量,而不是类变量。实际上,将组件添加到计算机会将它们添加到 all 其他组件。也就是说,每个组件都是每个其他组件的组件,这会导致无限循环。

_components