Python supports single inheritance with optional multiple inheritance—use sparingly. Subclasses override methods; call super with super() to extend parent behavior—like Java super or C# base.
Subclass example
class Animal:
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "woof"
class ServiceDog(Dog):
def speak(self):
base = super().speak()
return f"{base} (trained)"
Method Resolution Order (MRO)
Python uses C3 linearization for MRO—ClassName.__mro__ shows lookup order in multiple inheritance. Prefer composition over deep inheritance trees.
Important interview questions and answers
- Q: super() purpose?
A: Delegates to the next class in MRO—works with multiple inheritance unlike hard-coded parent names. - Q: Composition vs inheritance?
A: Favor has-a relationships when behavior can be shared without is-a taxonomies—especially in Django models later.
Self-check
- How call a parent method from a subclass?
- What does MRO stand for?
Pitfall: Deep inheritance hierarchies hurt maintenance—prefer composition for shared behavior.
Interview prep
- super() purpose?
Calls next method in MRO—supports cooperative multiple inheritance.
- Composition vs inheritance?
Prefer has-a when behavior sharing does not imply is-a taxonomy—especially in large apps.