0
0
Pythonprogramming~5 mins

Purpose of polymorphism in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Purpose of polymorphism
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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

As the number of animals grows, the program calls speak() for each one.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line as the number of animals increases.

Common Mistake

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

Interview Connect

Understanding how polymorphism affects time helps you explain your code clearly and shows you know how design choices impact performance.

Self-Check

"What if we added nested loops calling speak() multiple times per animal? How would the time complexity change?"