Method overriding in Python - Time & Space Complexity
When we use method overriding, we replace a method in a child class with a new version.
We want to see how this affects the time it takes to run the program.
Analyze the time complexity of the following code snippet.
class Animal:
def speak(self):
return "Sound"
class Dog(Animal):
def speak(self):
return "Bark"
animal = Animal()
dog = Dog()
print(animal.speak())
print(dog.speak())
This code shows a parent class with a method, and a child class that overrides that method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
speakmethod on objects. - How many times: Each method is called once in this example.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 method calls |
| 100 | 2 method calls |
| 1000 | 2 method calls |
Pattern observation: The number of operations is constant (2 method calls), regardless of input size n.
Time Complexity: O(1)
This means the time to run is constant; it does not grow with input size in this example.
[X] Wrong: "Overriding a method makes the program slower because it adds extra steps."
[OK] Correct: Overriding just changes which code runs; it does not add extra loops or repeated work by itself.
Understanding how method overriding works helps you explain how programs decide which code to run.
This skill shows you know how object-oriented programs organize and run their tasks efficiently.
"What if the overridden method called the parent method inside it? How would the time complexity change?"