Purpose of inheritance in Python - Time & Space 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?
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 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
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 |
|---|---|
| 10 | 10 calls to speak() |
| 100 | 100 calls to speak() |
| 1000 | 1000 calls to speak() |
Pattern observation: The work increases evenly as the number of pets increases.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of objects using inheritance.
[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.
Understanding how inheritance affects time helps you explain your code design choices clearly and shows you know how programs grow with more objects.
"What if the speak method called another method inside the parent class? How would the time complexity change?"