Introduction & Syntax
Inheritance and Polymorphism · Study material
Inheritance lets a new class reuse and extend an existing one: a Manager is an Employee with a bonus, an ElectricCar is a Car with a battery. Polymorphism lets different classes be used through the same interface – call shape.area() or channel.send() without caring about the exact type. Together they are the heart of OOP, and a guaranteed interview topic: super(), method overriding, multiple inheritance and the MRO, abstract classes, duck typing and operator overloading. This topic covers all of them, then 50 practice questions run on Python 3.
On this page
- Inheritance and method overriding
- super() and extending parent behaviour
- Multilevel, hierarchical and multiple inheritance; the MRO
- Abstract base classes
- Polymorphism and duck typing
- Operator overloading and mixins
Inheritance and overriding
class Dog(Animal): makes Dog a subclass of Animal: it inherits all of Animal's attributes and methods and can override any of them by defining a method with the same name. When a parent method calls self.speak(), Python looks up speak on the actual object, so the child's version runs – this dynamic dispatch is what makes inheritance powerful. isinstance(obj, Class) and issubclass(Sub, Base) test the relationships.
class Animal: # parent / base / super class
def __init__(self, name):
self.name = name
def speak(self):
return "..."
def describe(self):
return f"{self.name} says {self.speak()}"
class Dog(Animal): # child / derived / sub class
def speak(self): # overriding the parent method
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"
for pet in [Dog("Bruno"), Cat("Kitty"), Animal("Generic")]:
print(pet.describe()) # inherited describe() calls the CHILD's speak()
print(isinstance(Dog("x"), Animal), issubclass(Cat, Animal), issubclass(Animal, Dog))
Bruno says Woof Kitty says Meow Generic says ... True True False
super(): extending instead of replacing
A child that defines its own __init__ replaces the parent's – so call super().__init__(...) to let the parent initialise its attributes. Likewise super().method() inside an override reuses the parent's logic and adds to it. Forgetting super().__init__() is a classic bug: the parent's attributes never get created.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def pay(self):
return self.salary
def __str__(self):
return f"{self.name}: Rs {self.pay():,}"
class Manager(Employee):
def __init__(self, name, salary, bonus):
super().__init__(name, salary) # let the parent set up its part
self.bonus = bonus # then add the child's own data
def pay(self):
return super().pay() + self.bonus # extend, not replace, the parent behaviour
staff = [Employee("Ravi", 50000), Manager("Asha", 90000, 15000)]
for e in staff:
print(e) # __str__ is inherited; pay() is dispatched per object
print(sum(e.pay() for e in staff))
Ravi: Rs 50,000 Asha: Rs 105,000 155000
Multilevel and hierarchical inheritance
Classes can form chains (multilevel: Vehicle → Car → ElectricCar) and trees (hierarchical: Car and Bike both inherit from Vehicle). Attribute lookup walks up the chain until it finds the name; every class ultimately inherits from object. Class.__mro__ shows the exact lookup order.
class Vehicle:
wheels = 0
def info(self):
return f"{type(self).__name__} with {self.wheels} wheels"
class Car(Vehicle): # Vehicle -> Car (single)
wheels = 4
class ElectricCar(Car): # Vehicle -> Car -> ElectricCar (multilevel)
def info(self):
return super().info() + ", battery powered"
class Bike(Vehicle): # Vehicle -> Bike (hierarchical: two children of one parent)
wheels = 2
for v in [Car(), ElectricCar(), Bike()]:
print(v.info())
print([c.__name__ for c in ElectricCar.__mro__])
Car with 4 wheels ElectricCar with 4 wheels, battery powered Bike with 2 wheels ['ElectricCar', 'Car', 'Vehicle', 'object']
Multiple inheritance and the MRO
A class may inherit from several parents: class D(B, C). Python linearises the hierarchy into the method resolution order (C3 algorithm): the class itself, then its parents left to right, with every class appearing once and only after all its children. In the "diamond" (B and C both inherit from A), super() follows the MRO – not simply "the parent" – so each class runs exactly once. If no consistent order exists, Python refuses to create the class.
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B -> " + super().hello()
class C(A):
def hello(self):
return "C -> " + super().hello()
class D(B, C): # multiple inheritance: the "diamond"
def hello(self):
return "D -> " + super().hello()
print([cls.__name__ for cls in D.__mro__])
print(D().hello()) # super() follows the MRO, so A runs once
['D', 'B', 'C', 'A', 'object'] D -> B -> C -> A
Abstract base classes
An abstract base class (from the abc module) defines an interface: methods marked @abstractmethod must be implemented by subclasses. The abstract class itself cannot be instantiated, nor can any subclass that leaves an abstract method unimplemented – the error appears at creation time, not deep inside later code.
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self): # every concrete shape MUST implement this
...
def describe(self): # shared behaviour built on the abstract method
return f"{type(self).__name__} with area {self.area():.2f}"
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
for s in [Circle(1), Square(3)]:
print(s.describe())
try:
Shape()
except TypeError:
print("TypeError: cannot instantiate the abstract class Shape")
Circle with area 3.14 Square with area 9.00 TypeError: cannot instantiate the abstract class Shape
Polymorphism and duck typing
Polymorphism means one interface, many implementations. In Python it does not even need a common parent: "if it walks like a duck and quacks like a duck, it is a duck". Any object with a send() method can be passed to notify_all(). Built-ins work the same way – len(), for, + and in work on any object that implements the matching dunder method.
class Email:
def send(self, msg):
return f"Email: {msg}"
class SMS:
def send(self, msg):
return f"SMS: {msg[:20]}"
class WhatsApp:
def send(self, msg):
return f"WhatsApp: {msg} ✓✓"
def notify_all(channels, msg):
# Duck typing: any object with a send() method works – no common parent needed
return [c.send(msg) for c in channels]
for line in notify_all([Email(), SMS(), WhatsApp()], "Your exam result is out"):
print(line)
print(len("abc"), len([1, 2]), len({"a": 1})) # built-in polymorphism: one len(), many types
Email: Your exam result is out SMS: Your exam result is WhatsApp: Your exam result is out ✓✓ 3 2 1
Operator overloading
Defining dunder methods makes operators work with your classes: __add__ for +, __mul__ for *, __lt__ and __eq__ for comparisons, __len__, __getitem__ and more. Return NotImplemented for unsupported types so Python can try the other operand's reflected method (__radd__). sum() starts from 0, so it needs __radd__ to accept 0 + Money(…).
class Money:
def __init__(self, rupees):
self.rupees = rupees
def __add__(self, other): # money + money (or + a number)
if isinstance(other, Money):
return Money(self.rupees + other.rupees)
if isinstance(other, (int, float)):
return Money(self.rupees + other)
return NotImplemented
__radd__ = __add__ # number + money – lets sum() start from 0
def __mul__(self, factor): # money * 3
return Money(self.rupees * factor)
def __lt__(self, other): # enables <, and so sorted(), min(), max()
return self.rupees < other.rupees
def __repr__(self):
return f"Rs {self.rupees}"
prices = [Money(250), Money(99), Money(400)]
print(Money(100) + Money(50), Money(100) * 3, 10 + Money(5))
print(sum(prices), min(prices), sorted(prices))
Rs 150 Rs 300 Rs 15 Rs 749 Rs 99 [Rs 99, Rs 250, Rs 400]
Common mistakes
- Forgetting super().__init__() – parent attributes are missing: AttributeError.
- A misspelt override (spek instead of speak) – the parent version runs silently.
- Calling self.method() inside the same override instead of super().method() – infinite recursion.
- Calling Parent.__init__(self) directly in a diamond – a shared base runs twice.
- Checking isinstance against the base class first in an if-elif – the subclass branch is never reached.
- Instantiating an abstract class – TypeError.
- Using sum() without __radd__ – TypeError for 0 + object.
Key points to remember
- A subclass inherits everything and may override any method.
- self.method() always dispatches to the object's actual class.
- super() delegates to the next class in the MRO.
- MRO: the class, then parents left to right, each class once, children before parents.
- Abstract classes define required methods and cannot be instantiated.
- Duck typing: behaviour matters, not the class hierarchy.
- Dunder methods overload operators; return NotImplemented when unsupported.
Frequently asked questions
Does Python support method overloading (same name, different parameters)?
Not directly: a later def replaces an earlier one. Use default arguments, *args, or functools.singledispatch instead. Method overriding (in subclasses) is fully supported.
Composition or inheritance?
Inherit when the child truly "is a" kind of parent; otherwise prefer composition ("has a"): store an object as an attribute and call it.
Is multiple inheritance a good idea?
Used for small mixins that each add one capability, it works well. Deep diamond hierarchies with state in several parents become hard to follow.
Where can I learn more?
Read Python Inheritance and Dunder Methods and Dataclasses in the Python tutorial, then practise with the exercises below.