0
0
Pythonprogramming~5 mins

Parent and child classes in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parent and child classes
O(n)
Understanding Time Complexity

When using parent and child classes, it's important to see how the program runs as the number of objects grows.

We want to know how the time to run changes when we create or use many class instances.

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):
        super().greet()
        print("Hello from Child")

children = [Child() for _ in range(n)]
for child in children:
    child.greet()
    

This code creates a list of child objects and calls a method on each one that also calls the parent method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of child objects and calling the greet method on each.
  • How many times: The loop runs once for each child object, so n times.
How Execution Grows With Input

As the number of child objects increases, the total work grows in a straight line with n.

Input Size (n)Approx. Operations
10About 10 greet calls
100About 100 greet calls
1000About 1000 greet calls

Pattern observation: Doubling the number of objects doubles the total calls and work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of child objects created and used.

Common Mistake

[X] Wrong: "Calling a method on child classes that use parent methods makes the program slower in a way that grows faster than the number of objects."

[OK] Correct: Each method call is simple and happens once per object, so the total time grows just with the number of objects, not faster.

Interview Connect

Understanding how loops over class instances affect time helps you explain object-oriented code performance clearly and confidently.

Self-Check

"What if the greet method called itself recursively inside the child class? How would the time complexity change?"