From c5e40ea97eea3e1b51e45f146a23ba0da72de03f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Bonilla=20Mart=C3=ADnez?= Date: Thu, 9 Aug 2018 09:29:44 +0200 Subject: [PATCH] Update composite.py Defining component interface instead of doing super in __init__ Getting rid of map function because not results showed on execution time Support for python2 and python3 Using abc to define interfaces --- composite.py | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/composite.py b/composite.py index f6f2c9d..d5855c3 100644 --- a/composite.py +++ b/composite.py @@ -1,36 +1,39 @@ -class Component(object): - def __init__(self, *args, **kw): - pass +import abc + + +class ComponentInterface(object): + __metaclass__ = abc.ABCMeta + @abc.abstractmethod def component_function(self): pass -class Leaf(Component): - def __init__(self, *args, **kw): - Component.__init__(self, *args, **kw) +class Leaf(ComponentInterface): + def __init__(self, number): + self.number = number def component_function(self): - print "some function" + print("i'm leaf number: {}".format(self.number)) -class Composite(Component): - def __init__(self, *args, **kw): - Component.__init__(self, *args, **kw) - self.children = [] +class Composite(ComponentInterface): + def __init__(self): + self._children = set() def append_child(self, child): - self.children.append(child) + self._children.add(child) def remove_child(self, child): - self.children.remove(child) + self._children.remove(child) def component_function(self): - map(lambda x: x.component_function(), self.children) - -c = Composite() -l = Leaf() -l_two = Leaf() -c.append_child(l) -c.append_child(l_two) -c.component_function() + for child in self._children: + child.component_function() + + +if __name__ == '__main__': + composite = Composite() + for number in range(2): + composite.append_child(Leaf(number)) + composite.component_function()