Reusing and Extending Code with Ease
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that lets one class inherit attributes and behaviors (methods) from another class.
Think of it like a family tree:
- You inherit traits from your parents — eye color, height, certain habits.
- Similarly, a child class inherits properties and methods from a parent (base) class.
In Python, inheritance allows you to create a new class that reuses, extends, or modifies the behavior of an existing class.
Why Use Inheritance? #
- Code Reusability: Write common code once in a base class and reuse it in many child classes.
- Maintainability: Fix or update code in one place (base class) and all subclasses benefit.
- Extensibility: Add new features by extending existing classes without rewriting everything.
- Polymorphism: Different classes can be treated the same way if they share a common base.
Basic Terminology #
Term | Meaning |
---|---|
Base Class / Parent Class | The class whose properties are inherited |
Derived Class / Child Class | The class that inherits from the base class |
Subclass | Another name for derived/child class |
Superclass | Another name for base/parent class |
How to Use Inheritance in Python? #
You define a child class that inherits from a parent class by putting the parent class name inside parentheses after the child class name.
Simple Example: Basic Inheritance #
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
class Dog(Animal):
def speak(self):
print(f"{self.name} barks.")
class Cat(Animal):
def speak(self):
print(f"{self.name} meows.")
# Using the classes:
dog = Dog("Buddy")
cat = Cat("Whiskers")
dog.speak() # Buddy barks.
cat.speak() # Whiskers meows.
What’s happening here? #
Animal
is the base class with an__init__
andspeak
method.Dog
andCat
are child classes inheriting fromAnimal
.- Both override the
speak
method with their own version. - You get to reuse the
__init__
method fromAnimal
without rewriting it in each child.
Calling Parent Class Methods in Child Class #
Sometimes, you want to extend the behavior of a parent method rather than fully replace it.
You can do this with the super()
function:
class Bird(Animal):
def speak(self):
super().speak() # Call the parent speak method
print(f"{self.name} chirps happily.")
bird = Bird("Tweety")
bird.speak()
# Output:
# Tweety makes a sound.
# Tweety chirps happily.
Here, super().speak()
calls the speak
method of the base class Animal
, then the child adds more behavior.
Multiple Inheritance: Inheriting from More Than One Class #
Python supports multiple inheritance, where a class can inherit from multiple base classes.
Example:
class Flyer:
def fly(self):
print("I can fly!")
class Swimmer:
def swim(self):
print("I can swim!")
class Duck(Animal, Flyer, Swimmer):
def speak(self):
print(f"{self.name} quacks.")
duck = Duck("Donald")
duck.speak() # Donald quacks.
duck.fly() # I can fly!
duck.swim() # I can swim!
Duck
inherits fromAnimal
,Flyer
, andSwimmer
.- It gets methods from all three parent classes.
Method Resolution Order (MRO) #
When using inheritance, especially multiple inheritance, Python uses the Method Resolution Order to decide which method to call.
You can check the MRO by:
print(Duck.mro())
It returns a list showing the order in which Python looks for methods.
Inheritance Types in Python #
Type | Description |
---|---|
Single Inheritance | One child class inherits from one parent class |
Multiple Inheritance | One child class inherits from multiple parent classes |
Multilevel Inheritance | Child class inherits from a parent class, which itself inherits from another class |
Hierarchical Inheritance | Multiple child classes inherit from a single parent class |
Multilevel Inheritance Example #
class Vehicle:
def start(self):
print("Starting the vehicle.")
class Car(Vehicle):
def drive(self):
print("Driving the car.")
class SportsCar(Car):
def turbo(self):
print("Turbo mode activated!")
car = SportsCar()
car.start() # Inherited from Vehicle
car.drive() # Inherited from Car
car.turbo() # Own method
Real-World Use Case: User Management System #
Imagine you are building a system with different user types:
- Base class:
User
with basic user info. - Child classes:
AdminUser
,GuestUser
,RegisteredUser
with specific permissions.
class User:
def __init__(self, username):
self.username = username
def login(self):
print(f"{self.username} logged in.")
def logout(self):
print(f"{self.username} logged out.")
class AdminUser(User):
def delete_user(self, user):
print(f"Admin {self.username} deleted user {user.username}.")
class GuestUser(User):
def browse(self):
print(f"Guest {self.username} is browsing.")
class RegisteredUser(User):
def purchase(self, item):
print(f"{self.username} purchased {item}.")
# Usage:
admin = AdminUser("Alice")
guest = GuestUser("Bob")
registered = RegisteredUser("Charlie")
admin.login()
guest.browse()
registered.purchase("Book")
admin.delete_user(registered)
Overriding vs Overloading #
- Overriding: Child class provides a new version of a parent method (seen in the examples above).
- Overloading: Python doesn’t support method overloading directly, but you can simulate it with default parameters or variable arguments.
Key Points to Remember #
- Use inheritance to avoid duplicating code.
- Use
super()
to call parent class methods safely. - Be careful with multiple inheritance — understand MRO.
- Keep your inheritance hierarchy logical and simple.
- Prefer composition over inheritance if it leads to clearer code.
Summary #
Inheritance is a powerful OOP tool that:
- Promotes code reuse and cleaner design.
- Lets child classes inherit and customize behaviors.
- Supports complex relationships with multiple and multilevel inheritance.
- Enables polymorphism — treating different subclasses uniformly.