|
28 | 28 | Allows the interface of an existing class to be used as another interface.
|
29 | 29 | """
|
30 | 30 |
|
| 31 | +from typing import Callable, TypeVar |
| 32 | + |
| 33 | +T = TypeVar("T") |
| 34 | + |
31 | 35 |
|
32 | 36 | class Dog:
|
33 |
| - def __init__(self): |
| 37 | + def __init__(self) -> None: |
34 | 38 | self.name = "Dog"
|
35 | 39 |
|
36 |
| - def bark(self): |
| 40 | + def bark(self) -> str: |
37 | 41 | return "woof!"
|
38 | 42 |
|
39 | 43 |
|
40 | 44 | class Cat:
|
41 |
| - def __init__(self): |
| 45 | + def __init__(self) -> None: |
42 | 46 | self.name = "Cat"
|
43 | 47 |
|
44 |
| - def meow(self): |
| 48 | + def meow(self) -> str: |
45 | 49 | return "meow!"
|
46 | 50 |
|
47 | 51 |
|
48 | 52 | class Human:
|
49 |
| - def __init__(self): |
| 53 | + def __init__(self) -> None: |
50 | 54 | self.name = "Human"
|
51 | 55 |
|
52 |
| - def speak(self): |
| 56 | + def speak(self) -> str: |
53 | 57 | return "'hello'"
|
54 | 58 |
|
55 | 59 |
|
56 | 60 | class Car:
|
57 |
| - def __init__(self): |
| 61 | + def __init__(self) -> None: |
58 | 62 | self.name = "Car"
|
59 | 63 |
|
60 |
| - def make_noise(self, octane_level): |
61 |
| - return "vroom{0}".format("!" * octane_level) |
| 64 | + def make_noise(self, octane_level: int) -> str: |
| 65 | + return f"vroom{'!' * octane_level}" |
62 | 66 |
|
63 | 67 |
|
64 | 68 | class Adapter:
|
65 |
| - """ |
66 |
| - Adapts an object by replacing methods. |
67 |
| - Usage: |
| 69 | + """Adapts an object by replacing methods. |
| 70 | +
|
| 71 | + Usage |
| 72 | + ------ |
68 | 73 | dog = Dog()
|
69 | 74 | dog = Adapter(dog, make_noise=dog.bark)
|
70 | 75 | """
|
71 | 76 |
|
72 |
| - def __init__(self, obj, **adapted_methods): |
73 |
| - """We set the adapted methods in the object's dict""" |
| 77 | + def __init__(self, obj: T, **adapted_methods: Callable): |
| 78 | + """We set the adapted methods in the object's dict.""" |
74 | 79 | self.obj = obj
|
75 | 80 | self.__dict__.update(adapted_methods)
|
76 | 81 |
|
77 | 82 | def __getattr__(self, attr):
|
78 |
| - """All non-adapted calls are passed to the object""" |
| 83 | + """All non-adapted calls are passed to the object.""" |
79 | 84 | return getattr(self.obj, attr)
|
80 | 85 |
|
81 | 86 | def original_dict(self):
|
82 |
| - """Print original object dict""" |
| 87 | + """Print original object dict.""" |
83 | 88 | return self.obj.__dict__
|
84 | 89 |
|
85 | 90 |
|
@@ -116,4 +121,5 @@ def main():
|
116 | 121 |
|
117 | 122 | if __name__ == "__main__":
|
118 | 123 | import doctest
|
| 124 | + |
119 | 125 | doctest.testmod(optionflags=doctest.ELLIPSIS)
|
0 commit comments