0
0
Pythonprogramming~5 mins

Purpose of inheritance in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Purpose of inheritance
O(n)
Understanding Time Complexity

When we use inheritance in Python, we want to see how the program's running time changes as we add more classes or objects.

We ask: How does the program's work grow when using inheritance?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

n = 10  # example value for n
pets = [Dog() for _ in range(n)]
for pet in pets:
    pet.speak()
    

This code creates a list of Dog objects that inherit from Animal and calls their speak method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of pets and calling speak()
  • How many times: Once for each pet, so n times
How Execution Grows With Input

Each pet in the list calls its speak method once, so the work grows directly with the number of pets.

Input Size (n)Approx. Operations
1010 calls to speak()
100100 calls to speak()
10001000 calls to speak()

Pattern observation: The work increases evenly as the number of pets increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of objects using inheritance.

Common Mistake

[X] Wrong: "Inheritance makes the program slower because it adds extra steps for each method call."

[OK] Correct: The extra steps are very small and do not multiply with the number of objects; the main time depends on how many times methods are called, not inheritance itself.

Interview Connect

Understanding how inheritance affects time helps you explain your code design choices clearly and shows you know how programs grow with more objects.

Self-Check

"What if the speak method called another method inside the parent class? How would the time complexity change?"