Inheriting attributes and methods in Python - Time & Space Complexity
When we use inheritance in Python, we want to know how it affects the time it takes to run our program.
We ask: How does accessing inherited attributes or methods grow as our program runs?
Analyze the time complexity of accessing inherited attributes and methods.
class Animal:
def speak(self):
return "Sound"
class Dog(Animal):
def speak(self):
return "Bark"
pet = Dog()
print(pet.speak())
This code shows a class Dog inheriting from Animal and overriding the speak method.
Look for repeated actions that affect time.
- Primary operation: Method call pet.speak()
- How many times: Once in this example, but could be many in a program
Accessing an inherited method takes about the same time no matter how many classes are involved.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 method calls, each quick |
| 100 | 100 method calls, each quick |
| 1000 | 1000 method calls, each quick |
Pattern observation: Each method call takes a small, steady amount of time regardless of inheritance depth.
Time Complexity: O(1)
This means calling an inherited method takes a constant amount of time no matter how many times you do it.
[X] Wrong: "Calling an inherited method gets slower if the parent class has many methods or deep inheritance."
[OK] Correct: Python looks up methods efficiently, so the time to find and run a method stays about the same.
Understanding that inheritance does not slow down method calls helps you write clear and efficient code confidently.
What if we added many layers of inheritance? How would the time complexity of calling a method change?