Polymorphism through inheritance in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
Let's see how the time taken by a program changes when using polymorphism through inheritance.
We want to know how the program's steps grow as we use more objects with inherited behaviors.
Analyze the time complexity of the following code snippet.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof")
class Cat(Animal):
def speak(self):
print("Meow")
animals = [Dog(), Cat(), Dog()]
for animal in animals:
animal.speak()
This code creates a list of animals and calls their speak method, which behaves differently depending on the animal type.
- Primary operation: Looping through the list of animals and calling their speak method.
- How many times: Once for each animal in the list.
Each animal in the list causes one speak call, so the work grows as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 speak calls |
| 100 | 100 speak calls |
| 1000 | 1000 speak calls |
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 you add more animals to the list.
[X] Wrong: "Polymorphism makes the program slower because it adds extra steps for each method call."
[OK] Correct: The extra steps are very small and do not change how the total time grows with more animals; the main factor is still how many animals you have.
Understanding how polymorphism affects time helps you explain your code's behavior clearly and shows you know how programs scale with more data.
"What if we added a nested loop inside each speak method? How would the time complexity change?"
Practice
Solution
Step 1: Understand polymorphism concept
Polymorphism means one method name can behave differently depending on the class.Step 2: Relate to inheritance
Child classes override the method to provide their own behavior.Final Answer:
One method name to have different behaviors in child classes -> Option AQuick Check:
Polymorphism = One method, many behaviors [OK]
- Confusing polymorphism with multiple inheritance
- Thinking polymorphism means same variable names
- Believing objects can exist without classes
Solution
Step 1: Check method overriding syntax
In Python, overriding means defining a method with the same name in the child class.Step 2: Verify other options
Python does not useoverridekeyword; renaming is not overriding; calling parent method alone is not overriding.Final Answer:
Define a method with the same name in the child class -> Option CQuick Check:
Override = same method name in child [OK]
- Using a non-existent
overridekeyword - Thinking calling parent method equals overriding
- Renaming method instead of overriding
class Animal:
def sound(self):
return "Some sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
animals = [Dog(), Cat(), Animal()]
for a in animals:
print(a.sound())Solution
Step 1: Identify method overriding
Dog and Cat classes overridesoundmethod to return "Bark" and "Meow" respectively.Step 2: Trace the loop output
Loop callssound()on Dog(), Cat(), and Animal() objects, printing "Bark", "Meow", and "Some sound".Final Answer:
Bark Meow Some sound -> Option AQuick Check:
Overridden methods print their own sounds [OK]
- Assuming parent method always runs
- Expecting errors from calling base class method
- Mixing output order
class Vehicle:
def move(self):
print("Moving")
class Car(Vehicle):
def move(self):
print("Driving")
class Bike(Vehicle):
def move(self):
print("Riding")
vehicles = [Car(), Bike()]
for v in vehicles:
v.moveSolution
Step 1: Check method calls in loop
The code usesv.movewithout parentheses, so method is not called.Step 2: Understand effect of missing parentheses
Without parentheses, method object is referenced but not executed, so no output occurs.Final Answer:
Missing parentheses when callingmovemethod -> Option DQuick Check:
Method call needs () to execute [OK]
- Forgetting parentheses on method calls
- Thinking print vs return causes error here
- Believing inheritance syntax is wrong
Bird that also uses polymorphism with sound(). Which code correctly extends the existing classes and uses polymorphism?Solution
Step 1: Check inheritance and method name
Bird must inherit from Animal and overridesound()method to maintain polymorphism.Step 2: Verify method behavior and usage
Method returns string "Chirp" like others; appending Bird() to animals list and callingsound()works correctly.Final Answer:
Correctly inherits Animal and overrides sound() returning "Chirp" -> Option BQuick Check:
Polymorphism needs same method name and inheritance [OK]
- Not inheriting from Animal class
- Using different method name like noise()
- Printing inside method instead of returning
