Browse Python Topics ▼
Pick a Web Framework

Inheritance and Polymorphism in Python

📂 Object-Oriented Programming 📘 Lesson 34 of 57

Extend and specialize classes with inheritance, reuse parent logic using super(), override methods, and achieve dynamic polymorphism across object hierarchies.

Imagine you are building a video game featuring dozens of vehicles: cars, motorcycles, helicopters, and submarines.

Every single vehicle shares core properties:

  • Attributes: speed, fuel_level, brand, color.
  • Behaviors: accelerate(), brake(), refuel().

If you created separate, unrelated classes for Car, Motorcycle, and Helicopter, you would find yourself copying and pasting the exact same accelerate() and refuel() methods dozens of times across your project.

Instead of writing repetitive code, Object-Oriented Programming gives you Inheritance: the ability to create a general base class and have specialized child classes automatically inherit its properties and behaviors.


1. The Core Syntax of Inheritance

To inherit from an existing class, pass the parent class name inside parentheses after the child class definition:

class ChildClass(ParentClass):
# Base (Parent) Class
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model
        self.speed = 0

    def accelerate(self, mph):
        self.speed += mph
        print(f"{self.brand} {self.model} accelerated to {self.speed} mph.")

    def brake(self):
        self.speed = 0
        print(f"{self.brand} {self.model} stopped.")

# Derived (Child) Class
class Motorcycle(Vehicle):
    # Motorcycle inherits all attributes and methods of Vehicle automatically!
    def pop_wheelie(self):
        print(f"{self.brand} {self.model} popped a thrilling wheelie!")

bike = Motorcycle("Yamaha", "MT-07")

# Inherited methods work effortlessly:
bike.accelerate(45)
# Specialized child behavior:
bike.pop_wheelie()
bike.brake()

Output:

Yamaha MT-07 accelerated to 45 mph.
Yamaha MT-07 popped a thrilling wheelie!
Yamaha MT-07 stopped.

The “IS-A” Rule

Inheritance models an “IS-A” relationship:

  • A Motorcycle is a Vehicle.
  • A Dog is an Animal.
  • A CheckingAccount is a BankAccount.

If the relationship between two concepts is not “IS-A”, inheritance is probably the wrong design choice.


2. Reusing Initialization with super()

What happens if a child class needs additional attributes that the parent does not have?

If you define a new __init__ method in the child class, Python overrides the parent’s __init__. To initialize the shared parent attributes without rewriting them, use super():

class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

class ElectricCar(Vehicle):
    def __init__(self, brand, model, battery_capacity_kwh):
        # 1. Call parent constructor using super()
        super().__init__(brand, model)
        # 2. Initialize child-specific attributes
        self.battery_kwh = battery_capacity_kwh

    def charge(self):
        print(f"Charging {self.brand} {self.model}'s {self.battery_kwh} kWh battery...")

ev = ElectricCar("Tesla", "Model 3", 75)
print(f"Car: {ev.brand} {ev.model} (Battery: {ev.battery_kwh} kWh)")
ev.charge()

Output:

Car: Tesla Model 3 (Battery: 75 kWh)
Charging Tesla Model 3's 75 kWh battery...

super() delegates initialization up to Vehicle, ensuring self.brand and self.model are set up properly, while allowing ElectricCar to specialize its unique battery logic.


3. Method Overriding

Sometimes a child class inherits a method from a parent, but needs to execute custom logic instead. A subclass can override any parent method simply by defining a method with the exact same name:

class Employee:
    def __init__(self, name, base_salary):
        self.name = name
        self.base_salary = base_salary

    def calculate_bonus(self):
        # Standard employee bonus is 5%
        return self.base_salary * 0.05

class Manager(Employee):
    def calculate_bonus(self):
        # Override: Managers receive 15% plus a fixed $2,000 leadership stipend
        return (self.base_salary * 0.15) + 2000.0

emp = Employee("Devin", 80000)
mgr = Manager("Sarah", 120000)

print(f"{emp.name}'s Bonus: ${emp.calculate_bonus():,.2f}")  # $4,000.00
print(f"{mgr.name}'s Bonus: ${mgr.calculate_bonus():,.2f}")  # $20,000.00

4. Polymorphism: One Interface, Many Forms

Polymorphism comes from the Greek words for “many shapes”. In programming, it refers to the ability to treat different objects through a shared, uniform interface.

Because all specialized objects share common method names, a single function can work with any of them:

class PDFExporter:
    def export(self, document_title):
        print(f"Exporting '{document_title}' to format: PDF document.")

class CSVExporter:
    def export(self, document_title):
        print(f"Exporting '{document_title}' to format: Comma-separated CSV.")

class JSONExporter:
    def export(self, document_title):
        print(f"Exporting '{document_title}' to format: JSON payload.")

def publish_report(exporter, title):
    # This function doesn't care which exporter it received!
    # As long as the object has an export() method, it works seamlessly!
    exporter.export(title)

tools = [PDFExporter(), CSVExporter(), JSONExporter()]

for tool in tools:
    publish_report(tool, "Annual Financial Report")

Output:

Exporting 'Annual Financial Report' to format: PDF document.
Exporting 'Annual Financial Report' to format: Comma-separated CSV.
Exporting 'Annual Financial Report' to format: JSON payload.

Python’s “Duck Typing”

In statically typed languages like Java, objects must inherit from a common interface to be polymorphic. Python uses Duck Typing:

“If it walks like a duck and quacks like a duck, it’s a duck.”

If an object provides the expected method (export()), Python will call it happily regardless of class heritage!


5. Checking Types: isinstance() and issubclass()

car = ElectricCar("Tesla", "Model Y", 82)

# Check if an object is an instance of a class (or any of its parents):
print(isinstance(car, ElectricCar))  # True
print(isinstance(car, Vehicle))      # True (Because ElectricCar inherits from Vehicle!)
print(isinstance(car, Motorcycle))   # False

# Check relationship between classes directly:
print(issubclass(ElectricCar, Vehicle))  # True

6. Composition vs Inheritance: The Golden Rule

A frequent architectural trap for beginners is overusing inheritance:

# BAD DESIGN: Inheritance abused
class Car(Engine):  # Does a car "IS-AN" engine? No! A car "HAS-AN" engine!
    pass

The Rule of Thumb:

  • Use Inheritance for “IS-A” relationships (Manager IS-AN Employee).
  • Use Composition for “HAS-A” relationships (Car HAS-AN Engine, User HAS-AN Address).

In composition, you store objects inside attributes rather than inheriting:

# GOOD DESIGN: Composition
class Engine:
    def start(self):
        print("Vroom! Engine running.")

class Car:
    def __init__(self):
        self.engine = Engine()  # Composition!

    def drive(self):
        self.engine.start()

Summary & What’s Next

  • Inheritance lets subclasses reuse and extend parent attributes and methods.
  • Use super().__init__(...) to reuse parent initialization logic.
  • Override parent methods by defining a method with the same name in the child class.
  • Polymorphism lets different objects respond to identical method names.
  • Always prefer composition (“HAS-A”) over deep inheritance trees.

How do you protect sensitive object attributes from being tampered with directly? Learn how to guard your data with encapsulation.

Test your understanding of Inheritance and Polymorphism in Python

Quick interactive practice questions with instant feedback.

Take Quiz →