Purpose of polymorphism in Python - Time & Space Complexity
We want to understand how the time cost changes when using polymorphism in Python programs.
Specifically, we ask: How does polymorphism affect the number of steps a program takes as input grows?
Analyze the time complexity of this polymorphic code snippet.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
animals = [Dog(), Cat(), Dog()]
for animal in animals:
print(animal.speak())
This code creates different animals and calls their speak method using polymorphism.
Look for loops or repeated calls that affect time.
- Primary operation: Looping over the list of animals and calling speak()
- How many times: Once for each animal in the list
As the number of animals grows, the program calls speak() for each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to speak() |
| 100 | 100 calls to speak() |
| 1000 | 1000 calls to speak() |
Pattern observation: The number of operations grows directly with the number of animals.
Time Complexity: O(n)
This means the time grows in a straight line as the number of animals increases.
[X] Wrong: "Polymorphism makes the program slower because it adds extra steps."
[OK] Correct: Polymorphism itself just lets us call methods on different objects easily. The time depends mostly on how many objects we have, not on polymorphism adding extra loops.
Understanding how polymorphism affects time helps you explain your code clearly and shows you know how design choices impact performance.
"What if we added nested loops calling speak() multiple times per animal? How would the time complexity change?"