-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
75 lines (53 loc) · 1.51 KB
/
Copy pathexample.py
File metadata and controls
75 lines (53 loc) · 1.51 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""Abstract Base Classes — enforce interfaces with abc module."""
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class InvalidShape(Shape):
pass # missing abstract methods
class Storage(ABC):
@abstractmethod
def save(self, data):
pass
@abstractmethod
def load(self, key):
pass
class MemoryStorage(Storage):
def __init__(self):
self._data = {}
def save(self, data):
key = str(len(self._data))
self._data[key] = data
return key
def load(self, key):
return self._data[key]
if __name__ == "__main__":
print("=== Valid implementation ===")
rect = Rectangle(4, 5)
print(f"area={rect.area()}, perimeter={rect.perimeter()}")
print("\n=== Cannot instantiate ABC directly ===")
try:
Shape()
except TypeError as e:
print(f" TypeError: {e}")
print("\n=== Incomplete subclass fails at instantiation ===")
try:
InvalidShape()
except TypeError as e:
print(f" TypeError: {e}")
print("\n=== Storage interface ===")
store = MemoryStorage()
key = store.save({"name": "Alice"})
print(store.load(key))