Abstract Classes
Using abc module
Interview Relevant: Design patterns
Abstract Classes
Define interfaces with abstract methods.
Code Examples
Abstract classes with ABC.
python
1from abc import ABC, abstractmethod
2
3class Shape(ABC):
4 @abstractmethod
5 def area(self):
6 pass
7
8 @abstractmethod
9 def perimeter(self):
10 pass
11
12 def describe(self): # Concrete method
13 return f"Area: {self.area()}"
14
15# Cannot instantiate abstract class
16# shape = Shape() # TypeError!
17
18class Rectangle(Shape):
19 def __init__(self, width, height):
20 self.width = width
21 self.height = height
22
23 def area(self):
24 return self.width * self.height
25
26 def perimeter(self):
27 return 2 * (self.width + self.height)
28
29rect = Rectangle(3, 4)
30print(rect.area()) # 12
31print(rect.describe()) # Area: 12