AdvancedPython Programming · Lesson 28 of 30 · Updated ·
Inheritance in Depth — Abstract Classes, Multiple Inheritance, MRO and Composition
In the OOP lesson you wrote class Manager(Employee) and called super().__init__(). That is single inheritance with one parent. Interviewers often go further: "What is an abstract class?", "Does Python support multiple inheritance?", "What is the diamond problem and how does Python solve it?". This lesson answers these with small, runnable programs.
1. Polymorphism: one call, many behaviours
Polymorphism means the same method call does different things for different classes. The calling code does not need if checks on the type.
class Payment:
def pay(self, amount):
return f"Paid Rs {amount}"
class UPI(Payment):
def pay(self, amount):
return f"Paid Rs {amount} by UPI"
class Card(Payment):
def pay(self, amount):
return f"Paid Rs {amount + amount * 2 // 100} by card (2% fee)"
for method in [UPI(), Card(), Payment()]:
print(method.pay(500))
Paid Rs 500 by UPI
Paid Rs 510 by card (2% fee)
Paid Rs 500
The loop works for any class that has a pay method. A new payment type can be added later without changing the loop.
2. Abstract base classes
In the example above nothing stops someone from writing a payment class that forgets pay. An abstract base class (ABC) is a parent class that cannot be used directly and that forces its children to write certain methods. You build one with the abc module.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
...
def describe(self): # a normal method children share
return f"{type(self).__name__} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
# forgot to write area()
print(Circle(2).describe())
for name, make in [("Shape", lambda: Shape()), ("Square", lambda: Square(3))]:
try:
make()
except TypeError:
print("Cannot create", name, "- TypeError")
Circle with area 12.57
Cannot create Shape - TypeError
Cannot create Square - TypeError
Both lines raise TypeError, and the message says the class is abstract (the exact wording differs between Python versions). The error appears when you try to create the object, not later when someone calls the missing method. That is the main benefit: mistakes are caught early. An abstract class can still have normal methods (describe) that all children reuse.
| Normal class | Abstract class | |
|---|---|---|
| Can create objects? | yes | no |
| Can have normal methods? | yes | yes |
| Forces children to write methods? | no | yes, the @abstractmethod ones |
Python has no separate interface keyword like Java. An ABC with only abstract methods plays the role of an interface.
3. Multiple inheritance
A Python class can have more than one parent. It gets the methods of all of them.
class Camera:
def take_photo(self):
return "click"
class Phone:
def call(self, number):
return f"calling {number}"
class SmartPhone(Camera, Phone):
pass
s = SmartPhone()
print(s.take_photo(), "|", s.call("9876543210"))
print(isinstance(s, Camera), isinstance(s, Phone))
click | calling 9876543210
True True
4. The diamond problem and the MRO
Trouble starts when two parents have a method with the same name, especially when both inherit from one common grandparent. The class shape looks like a diamond, so this is called the diamond problem: which version should run?
Python answers with the MRO (Method Resolution Order): a fixed list of classes that Python searches, in order, for any attribute. You can see it with ClassName.__mro__ or ClassName.mro().
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B"
class C(A):
def hello(self):
return "C"
class D(B, C):
pass
print(D().hello())
print([cls.__name__ for cls in D.__mro__])
B
['D', 'B', 'C', 'A', 'object']
The rules behind the MRO (an algorithm called C3 linearization) give an order where:
- a child always comes before its parents,
- parents keep the left-to-right order you wrote in
class D(B, C), - the common grandparent
Aappears only once, after both B and C.
If you write class D(C, B) instead, C comes first and D().hello() returns "C".
5. How super() really works
super() does not simply mean "my parent". It means "the next class after me in the MRO of the object". In a diamond this lets every class run exactly once.
class A:
def setup(self):
print("A setup")
class B(A):
def setup(self):
print("B setup")
super().setup()
class C(A):
def setup(self):
print("C setup")
super().setup()
class D(B, C):
def setup(self):
print("D setup")
super().setup()
D().setup()
D setup
B setup
C setup
A setup
Inside B, super() led to C, not A, because for a D object the MRO is D, B, C, A. A ran only once. If B and C had called A.setup(self) directly instead, A would have run twice. This is why you should use super() consistently in class hierarchies.
6. Mixins
A mixin is a small class that adds one feature and is meant to be mixed into other classes through multiple inheritance. It is not used alone.
import json
class JsonMixin:
def to_json(self):
return json.dumps(self.__dict__)
class Student(JsonMixin):
def __init__(self, name, cgpa):
self.name = name
self.cgpa = cgpa
class Course(JsonMixin):
def __init__(self, code, credits):
self.code = code
self.credits = credits
print(Student("Asha", 8.7).to_json())
print(Course("CS201", 4).to_json())
{"name": "Asha", "cgpa": 8.7}
{"code": "CS201", "credits": 4}
7. Composition: "has a" instead of "is a"
Inheritance models an is-a relation: a Manager is an Employee. Composition models a has-a relation: a Car has an Engine. With composition, one object holds another object as an attribute and calls it.
class Engine:
def __init__(self, cc):
self.cc = cc
def start(self):
return f"{self.cc}cc engine started"
class Car:
def __init__(self, model, engine):
self.model = model
self.engine = engine # a Car HAS an Engine
def start(self):
return f"{self.model}: {self.engine.start()}"
print(Car("Swift", Engine(1200)).start())
print(Car("Creta", Engine(1500)).start())
Swift: 1200cc engine started
Creta: 1500cc engine started
A common design rule is "prefer composition over inheritance". Deep inheritance trees are hard to change: a change in a parent affects every child. With composition you can swap parts (a different engine) without creating a new subclass for every combination.
Common mistakes
- Thinking
super()always means the direct parent; it means the next class in the MRO. - Calling a parent's method by name (
A.setup(self)) in a diamond, so it runs twice. - Forgetting to implement an abstract method and only finding out when the object is created.
- Using inheritance for a has-a relation (a
Carthat inherits fromEngine). - Building deep inheritance trees where a mixin or composition would be simpler.
Quick recap
- Polymorphism: the same method name behaves differently in different classes.
ABC+@abstractmethodmake a class that cannot be created and that forces children to implement methods.- Python supports multiple inheritance; the MRO decides which method wins.
super()goes to the next class in the MRO, so each class in a diamond runs once.- Mixins add one small feature; composition (has-a) is often better than inheritance (is-a).