Skip to content

Inheritance and Polymorphism

Extend classes with inheritance, override methods, use super(), and leverage polymorphism.

What you'll learn

  • Create subclasses that inherit from a parent class
  • Override and extend parent methods with super()
  • Understand single and multiple inheritance
  • Use isinstance() and issubclass() for type checks
  • Apply polymorphism through duck typing

Concept

Basic Inheritance

A subclass inherits all attributes and methods from its parent (base) class. Define a subclass by passing the parent in parentheses:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

class Dog(Animal):       # Dog inherits from Animal
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

Dog and Cat inherit the __init__ method from Animal but override the speak method with their own implementation. This is the core of polymorphism — the same method name behaves differently for different classes.

Using super()

The super() function calls the parent class's method. This is essential when you want to extend rather than replace the parent's behavior:

class Animal:
    def __init__(self, name):
        self.name = name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)   # call Animal.__init__
        self.breed = breed       # add Dog-specific attribute

rex = Dog("Rex", "Labrador")
print(rex.name)   # Rex (from Animal)
print(rex.breed)  # Labrador (from Dog)

Always call super().__init__() in a subclass constructor to ensure the parent's initialization runs. Without it, parent attributes would not be set.

Method Resolution Order (MRO)

Python supports multiple inheritance — a class can inherit from multiple parents. The MRO determines the order in which parent classes are searched for methods:

class Flying:
    def move(self):
        return "Flying"

class Swimming:
    def move(self):
        return "Swimming"

class Duck(Flying, Swimming):
    pass

d = Duck()
print(d.move())  # Flying — first in MRO
print(Duck.__mro__)  # shows the search order

Python uses the C3 linearization algorithm to compute a consistent MRO. You can inspect it with ClassName.__mro__ or ClassName.mro(). The diamond problem is resolved deterministically.

isinstance and issubclass

rex = Dog("Rex", "Labrador")
print(isinstance(rex, Dog))     # True
print(isinstance(rex, Animal))  # True — Dog is a subclass of Animal
print(issubclass(Dog, Animal))  # True

isinstance() returns True for both the class and its parents — this is why it is preferred over type(x) == Dog for type checks. It respects the inheritance hierarchy.

Polymorphism and Duck Typing

Python uses duck typing: "If it walks like a duck and quacks like a duck, it is a duck." You do not need inheritance to get polymorphism — any object with the right method works:

def make_it_speak(thing):
    return thing.speak()  # works with any object that has speak()

class Robot:
    def speak(self):
        return "Beep boop"

make_it_speak(Dog("Rex", "Lab"))  # Rex says Woof!
make_it_speak(Robot())             # Beep boop

The function does not care about the type — it only cares that the object has a speak() method. This is more flexible than strict inheritance-based polymorphism.

Abstract Base Classes

For when you want to enforce that subclasses implement certain methods, use the abc module:

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Circle(Shape):
    def __init__(self, r):
        self.r = r
    def area(self):
        import math
        return math.pi * self.r ** 2

# Shape()  # TypeError — cannot instantiate abstract class
c = Circle(5)  # OK — area() is implemented

Abstract base classes define an interface that subclasses must implement. Trying to instantiate a class with unimplemented abstract methods raises TypeError.

Example

              # Basic inheritance
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound"

    def __str__(self):
        return f"{type(self).__name__}({self.name})"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

# Using the classes
rex = Dog("Rex", "Labrador")
whiskers = Cat("Whiskers")
print(rex.speak())       # Rex says Woof!
print(whiskers.speak())  # Whiskers says Meow!
print(rex)               # Dog(Rex)

# isinstance checks
print(isinstance(rex, Dog))     # True
print(isinstance(rex, Animal))  # True
print(issubclass(Cat, Animal))  # True

# Polymorphism — duck typing
def make_it_speak(thing):
    return thing.speak()

class Robot:
    def speak(self):
        return "Beep boop"

for obj in [rex, whiskers, Robot()]:
    print(make_it_speak(obj))

# Abstract base class
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w
        self.h = h
    def area(self):
        return self.w * self.h

r = Rectangle(3, 4)
print(f"Rectangle area: {r.area()}")
            

Shows inheritance with super(), method overriding, isinstance/issubclass, polymorphism via duck typing (a Robot with speak() works alongside animals), and an abstract base class with @abstractmethod.

Try it

  • JSON Formatter

    Objects with inheritance hierarchies often serialize to JSON.

  • Case Converter

    Class naming conventions — PascalCase for classes, snake_case for methods.

Common mistakes

The mistake

Forgetting to call super().__init__() in a subclass constructor

The fix

If a subclass defines __init__, it must call super().__init__(...) to initialize parent attributes. Without it, parent attributes are not set, leading to AttributeError when accessing them.

The mistake

Using type(x) == MyClass instead of isinstance(x, MyClass)

The fix

type() does not respect inheritance — type(rex) == Animal is False even for a Dog. Always use isinstance() for type checks; it returns True for the class and all parent classes.

Related Cheatsheets

Practice Inheritance and Polymorphism

2 exercises

Practice Inheritance and Polymorphism

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors