-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path07_abstract_base_classes.py
More file actions
53 lines (41 loc) · 1.17 KB
/
Copy path07_abstract_base_classes.py
File metadata and controls
53 lines (41 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
from abc import ABC, abstractmethod
class Shape(ABC):
"""
Demonstrating Abstract Base Classes (ABC).
Classes inheriting from Shape MUST implement the abstract methods.
"""
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
def perimeter(self):
return 4 * self.side
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * (self.radius ** 2)
def perimeter(self):
import math
return 2 * math.pi * self.radius
# Testing the implementation
if __name__ == "__main__":
shapes = [Square(5), Circle(3)]
for shape in shapes:
print(f"Shape: {type(shape).__name__}")
print(f"Area: {shape.area():.2f}")
print(f"Perimeter: {shape.perimeter():.2f}")
print("-" * 20)
# Attempting to instantiate the abstract class will fail
try:
s = Shape()
except TypeError as e:
print(f"Error: {e}")