0
0
Pythonprogramming~5 mins

Method overriding behavior in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding behavior
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run a program changes when we use method overriding in Python.

Specifically, we ask: How does calling an overridden method affect the program's speed as the number of calls grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Parent:
    def greet(self):
        print("Hello from Parent")

class Child(Parent):
    def greet(self):
        print("Hello from Child")

n = 10  # Example value for n
for i in range(n):
    obj = Child()
    obj.greet()

This code creates a Child object n times and calls its overridden greet method each time.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating an object and calling the overridden greet method.
  • How many times: This happens once for each iteration in the loop, so n times.
How Execution Grows With Input

Each time we increase n, the number of times we create an object and call greet grows the same way.

Input Size (n)Approx. Operations
1010 object creations and 10 method calls
100100 object creations and 100 method calls
10001000 object creations and 1000 method calls

Pattern observation: The total work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line as the number of calls increases.

Common Mistake

[X] Wrong: "Method overriding makes the program slower by adding extra hidden steps each time a method is called."

[OK] Correct: Overriding just changes which method runs, but calling a method still takes about the same time as usual. The main cost is how many times you call it, not that it is overridden.

Interview Connect

Understanding how method calls behave when overridden helps you explain object-oriented code clearly and shows you know how programs scale with input size.

Self-Check

"What if we created the object once before the loop and called the method n times? How would the time complexity change?"