Python / Core Python Fundamentals Interview Questions
How does inheritance work in Python and what is method resolution order (MRO)?
Inheritance lets a child class reuse and extend behaviour from a parent class. Specify the parent in parentheses after the class name. The child gets all the parent's methods automatically and can override any of them.
class Animal: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError class Dog(Animal): def speak(self): return f'{self.name} says Woof!' class Cat(Animal): def speak(self): return f'{self.name} says Meow!' animals = [Dog('Rex'), Cat('Whiskers')] for a in animals: print(a.speak()) # polymorphism â same call, different behaviour
super() calls the parent class's version of a method, essential when overriding __init__ to extend rather than replace the parent's initialisation:
class ServiceDog(Dog): def __init__(self, name, service_type): super().__init__(name) # call Dog -> Animal __init__ self.service_type = service_type
Python supports multiple inheritance: class C(A, B):. The MRO (Method Resolution Order) determines which class's method is used when there is ambiguity. Python uses the C3 linearisation algorithm. Inspect it with ClassName.__mro__ or ClassName.mro(). The order goes left-to-right through the parent list, depth-first, with a rule ensuring every class appears before its own parents.
More Related questions...