agyanadda@gmail.com

Python Inheritance and Polymorphism

Object-Oriented Python 1 min read Updated Dec 4, 2026 Topic 24 of 32

Inheritance lets a new class (child) reuse and extend an existing class (parent).

class Dog(Animal): — Dog gets all of Animal's attributes and methods.

super()

Call the parent's method from the child, especially in __init__: super().__init__(name).

Overriding

A child can define a method with the same name to change its behaviour.

Polymorphism

Different classes share a method name, so the same code works with all of them: for shape in shapes: print(shape.area()).

Checking types

isinstance(obj, Animal) and issubclass(Dog, Animal).

Multiple inheritance

class C(A, B): — Python decides method order with the MRO (C.__mro__). Use it carefully; small mixin classes are a common, safe use.

Abstract classes

from abc import ABC, abstractmethod — a base class that cannot be created directly and forces children to implement certain methods.

Prefer composition (an object having another object) when "is-a" doesn't fit.

Example

Example — Shapes with an abstract base class Python
from abc import ABC, abstractmethod
import math

class Shape(ABC):
    def __init__(self, name):
        self.name = name

    @abstractmethod
    def area(self) -> float: ...

    def describe(self):
        return f"{self.name} with area {self.area():.2f}"

class Rectangle(Shape):
    def __init__(self, w, h):
        super().__init__("Rectangle")
        self.w, self.h = w, h

    def area(self):
        return self.w * self.h

class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)
        self.name = "Square"

class Circle(Shape):
    def __init__(self, r):
        super().__init__("Circle")
        self.r = r

    def area(self):
        return math.pi * self.r ** 2

for shape in [Rectangle(4, 5), Square(3), Circle(2)]:
    print(shape.describe())

print(isinstance(Square(2), Rectangle))

Output: Rectangle with area 20.00, Square with area 9.00, Circle with area 12.57, True. Trying Shape("x") would raise TypeError because Shape is abstract.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function calls the parent class's method?

Exercise 2 True / False

A class that inherits from ABC with an abstract method cannot be created directly.

Exercise 3 Fill in the Blank

Check an object's class family with ___(obj, Animal)

Frequently Asked Questions

Use it when the child truly is a kind of the parent (a Square is a Rectangle) and shares most behaviour. If one object just uses another (a Car has an Engine), store it as an attribute instead (composition).