Multiple inheritance syntax in Python - Time & Space Complexity
Let's explore how the time needed to create a class with multiple inheritance grows as we add more parent classes.
We want to see how the program's work changes when using multiple inheritance syntax.
Analyze the time complexity of the following code snippet.
class A:
def method(self):
print("A method")
class B:
def method(self):
print("B method")
class C(A, B):
pass
obj = C()
obj.method()
This code defines two parent classes and one child class that inherits from both. It then creates an object and calls a method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Python looks through the parent classes in order to find the method.
- How many times: It checks each parent class once in the order they are listed.
When the program looks for a method, it checks each parent class one by one until it finds it.
| Number of Parent Classes (n) | Approx. Checks |
|---|---|
| 2 | Up to 2 checks |
| 5 | Up to 5 checks |
| 10 | Up to 10 checks |
Pattern observation: The number of checks grows directly with the number of parent classes.
Time Complexity: O(n)
This means the time to find a method grows linearly with the number of parent classes.
[X] Wrong: "Multiple inheritance always makes method lookup instant because Python knows all parents at once."
[OK] Correct: Python checks parent classes one by one in order, so more parents mean more checks.
Understanding how multiple inheritance affects method lookup helps you explain how Python manages class relationships and performance.
"What if the child class overrides the method? How would that change the time complexity of method lookup?"