Abstract base classes overview in Python - Time & Space Complexity
When using abstract base classes in Python, it's important to understand how they affect the speed of your program.
We want to know how the time to run code changes as the program uses these classes more.
Analyze the time complexity of the following code snippet.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
n = 10
shapes = [Square(i) for i in range(1, n+1)]
areas = [shape.area() for shape in shapes]
This code defines an abstract base class and creates a list of objects that calculate areas.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
area()method on each shape object. - How many times: Once for each object in the list, so
ntimes.
Each new shape adds one more method call to calculate its area.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 area calculations |
| 100 | 100 area calculations |
| 1000 | 1000 area calculations |
Pattern observation: The number of operations grows directly with the number of shapes.
Time Complexity: O(n)
This means the time to compute all areas grows in a straight line as you add more shapes.
[X] Wrong: "Using abstract base classes makes the program run much slower because of extra checks."
[OK] Correct: The main cost is still calling methods on each object, which happens anyway. Abstract base classes add only a tiny, usually unnoticeable overhead.
Understanding how abstract base classes affect performance helps you write clear, organized code without worrying about big slowdowns.
"What if the area() method was recursive? How would the time complexity change?"