Parent and child classes in Python - Time & Space 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.
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 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.
As the number of child objects increases, the total work grows in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 greet calls |
| 100 | About 100 greet calls |
| 1000 | About 1000 greet calls |
Pattern observation: Doubling the number of objects doubles the total calls and work done.
Time Complexity: O(n)
This means the time to run grows directly with the number of child objects created and used.
[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.
Understanding how loops over class instances affect time helps you explain object-oriented code performance clearly and confidently.
"What if the greet method called itself recursively inside the child class? How would the time complexity change?"