-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.py
More file actions
53 lines (34 loc) · 1.17 KB
/
composite.py
File metadata and controls
53 lines (34 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
""" Composite is used to create a tree data structure """
class Component:
def __init__(self, *args, **kwargs) -> None:
pass
def component_function(self):
pass
class Child(Component):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.name = args[0]
def component_function(self):
print(self.name)
class Composite(Component):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.name = args[0]
# Create a variable to collect children
self.children = []
def append_child(self, child):
self.children.append(child)
def remove_child(self, child):
self.children.remove(child)
def component_function(self):
print(self.name)
for item in self.children:
item.component_function()
sub = Composite(' - Sub Menu 1')
sub_child_1 = Child(' -- Sub 1.1')
sub.append_child(sub_child_1)
sub_child_2 = Child(' -- Sub 1.2')
sub.append_child(sub_child_2)
top = Composite('Top Menu')
top.append_child(sub)
top.component_function()