0
0
Pythonprogramming~5 mins

Abstract base classes overview in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract base classes overview
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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 n times.
How Execution Grows With Input

Each new shape adds one more method call to calculate its area.

Input Size (n)Approx. Operations
1010 area calculations
100100 area calculations
10001000 area calculations

Pattern observation: The number of operations grows directly with the number of shapes.

Final Time Complexity

Time Complexity: O(n)

This means the time to compute all areas grows in a straight line as you add more shapes.

Common Mistake

[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.

Interview Connect

Understanding how abstract base classes affect performance helps you write clear, organized code without worrying about big slowdowns.

Self-Check

"What if the area() method was recursive? How would the time complexity change?"