-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.py
More file actions
executable file
·49 lines (35 loc) · 1.25 KB
/
adapter.py
File metadata and controls
executable file
·49 lines (35 loc) · 1.25 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
class Korean:
"""Korean speaker"""
def __init__(self):
self.name = "Korean"
def speak_korean(self):
return "An-neyong?"
class British:
"""English speaker"""
def __init__(self):
self.name = "British"
#Note the different method name here!
def speak_english(self):
return "Hello!"
class Adapter:
"""This changes the generic method name to individualized method names"""
def __init__(self, object, **adapted_method):
"""Change the name of the method"""
self._object = object
#Add a new dictionary item that establishes the mapping between the generic method name: speak() and the concrete method
#For example, speak() will be translated to speak_korean() if the mapping says so
self.__dict__.update(adapted_method)
def __getattr__(self, attr):
"""Simply return the rest of attributes!"""
return getattr(self._object, attr)
#List to store speaker objects
objects = []
#Create a Korean object
korean = Korean()
#Create a British object
british =British()
#Append the objects to the objects list
objects.append(Adapter(korean, speak=korean.speak_korean))
objects.append(Adapter(british, speak=british.speak_english))
for obj in objects:
print("{} says '{}'\n".format(obj.name, obj.speak()))