-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathadapter_best.py
62 lines (44 loc) · 1.61 KB
/
adapter_best.py
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
54
55
56
57
58
59
60
61
62
class Elf:
name = 'Galadriel'
def nall_nin(self):
print('Elf says: Calling the Overlord ...')
class Dwarf:
def estver_narho(self):
print('Dwarf says: Calling the Overlord ...')
class Human:
def ring_mig(self):
print('Human says: Calling the Overlord ...')
class MinionAdapter:
_initialised = False
def __init__(self, minion, **adapted_methods):
self.minion = minion
for key, value in adapted_methods.items():
func = getattr(self.minion, value)
self.__setattr__(key, func)
self._initialised = True
def __getattr__(self, attr):
"""Attributes not in Adapter are delegated to the minion"""
return getattr(self.minion, attr)
def __setattr__(self, key, value):
"""Set attributes normally during initialisation"""
if not self._initialised:
super().__setattr__(key, value)
else:
"""Set attributes on minion after initialisation"""
setattr(self.minion, key, value)
if __name__ == '__main__':
minion_adapters = [
MinionAdapter(Elf(), call_me='nall_nin'),
MinionAdapter(Dwarf(), call_me='estver_narho'),
MinionAdapter(Human(), call_me='ring_mig')
]
for adapter in minion_adapters:
adapter.call_me()
elf_adapter = minion_adapters[0]
print()
print(f'Name from Adapter: {elf_adapter.name}')
print(f'Name from Minion: {elf_adapter.minion.name}')
minion_adapters[0].name = 'Elrond'
print()
print(f'Name from Adapter: {elf_adapter.name}')
print(f'Name from Minion: {elf_adapter.minion.name}')