PYTHON INHERITANCE

Learn how inheritance allows one Python class to reuse the properties and methods of another class, with practical real-time examples from banking, vehicles, employees, e-commerce, and more.

What is Inheritance?

Inheritance is an important concept in Object-Oriented Programming (OOP). It allows a new class, called the child class, to reuse attributes and methods from an existing class, called the parent class.

Inheritance helps us avoid duplicate code and makes programs easier to maintain and extend.

Parent Class
Common Features
→
Child Class
Inherited + New Features

Parent Class

The class whose properties and methods are inherited by another class.

Child Class

The class that inherits properties and methods from the parent class.

Code Reuse

Existing functionality can be reused without writing the same code again.

Extensibility

A child class can add its own properties and methods while keeping inherited functionality.

1. Basic Inheritance Example

The simplest form of inheritance is when one child class inherits from one parent class.

Python Code
class Animal:
    def eat(self):
        print("Animal is eating")


class Dog(Animal):
    def bark(self):
        print("Dog is barking")


dog = Dog()

dog.eat()
dog.bark()
Output:
Animal is eating
Dog is barking

Here, Dog inherits the eat() method from Animal. The Dog class also has its own bark() method.

2. Real-Time Example: Employee Management

In a company, different types of employees may share common information such as name and employee ID. Specific employee types can then add their own behavior.

Python Code
class Employee:
    def __init__(self, name, employee_id):
        self.name = name
        self.employee_id = employee_id

    def show_details(self):
        print("Name:", self.name)
        print("Employee ID:", self.employee_id)


class Developer(Employee):
    def write_code(self):
        print(self.name, "is writing Python code")


developer = Developer("Rahul", "EMP101")

developer.show_details()
developer.write_code()
Output:
Name: Rahul
Employee ID: EMP101
Rahul is writing Python code

The Developer class automatically receives the constructor and show_details() method from Employee.

3. Using the Parent Constructor with super()

When a child class has its own constructor, we can use super() to call the parent class constructor.

Python Code
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary


class Manager(Employee):
    def __init__(self, name, salary, team_size):
        super().__init__(name, salary)
        self.team_size = team_size

    def show_manager(self):
        print("Name:", self.name)
        print("Salary:", self.salary)
        print("Team Size:", self.team_size)


manager = Manager("Priya", 75000, 8)

manager.show_manager()
Output:
Name: Priya
Salary: 75000
Team Size: 8

super().__init__() initializes the attributes defined by the parent class.

4. Real-Time Example: Banking System

A banking application may have a common BankAccount class and specialized account types such as savings accounts.

Python Code
class BankAccount:
    def __init__(self, account_number, balance):
        self.account_number = account_number
        self.balance = balance

    def show_balance(self):
        print("Account:", self.account_number)
        print("Balance:", self.balance)


class SavingsAccount(BankAccount):
    def add_interest(self, rate):
        interest = self.balance * rate / 100
        self.balance += interest
        print("Interest Added:", interest)


account = SavingsAccount("SB1001", 50000)

account.show_balance()
account.add_interest(5)

print("Updated Balance:", account.balance)
Output:
Account: SB1001
Balance: 50000
Interest Added: 2500.0
Updated Balance: 52500.0
5. Real-Time Example: Vehicle System

A general vehicle can contain common properties such as brand and model. Cars and bikes can inherit those properties.

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

    def start(self):
        print(self.brand, self.model, "started")


class Car(Vehicle):
    def open_trunk(self):
        print("Car trunk opened")


class Bike(Vehicle):
    def kick_start(self):
        print("Bike kick started")


car = Car("Toyota", "Fortuner")
bike = Bike("Honda", "Activa")

car.start()
car.open_trunk()

bike.start()
bike.kick_start()
Output:
Toyota Fortuner started
Car trunk opened
Honda Activa started
Bike kick started
6. Multilevel Inheritance

In multilevel inheritance, a class inherits from another child class, creating a chain of inheritance.

Python Code
class Grandparent:
    def family_name(self):
        print("Family Name: Sharma")


class Parent(Grandparent):
    def parent_role(self):
        print("Parent manages the family")


class Child(Parent):
    def child_role(self):
        print("Child is studying")


person = Child()

person.family_name()
person.parent_role()
person.child_role()
Output:
Family Name: Sharma
Parent manages the family
Child is studying

The Child class can access methods from both Parent and Grandparent.

7. Multiple Inheritance

Python also supports multiple inheritance, where one child class inherits from more than one parent class.

Python Code
class Camera:
    def take_photo(self):
        print("Photo captured")


class Phone:
    def make_call(self):
        print("Calling...")


class Smartphone(Camera, Phone):
    def browse_internet(self):
        print("Browsing internet")


phone = Smartphone()

phone.take_photo()
phone.make_call()
phone.browse_internet()
Output:
Photo captured
Calling...
Browsing internet

Smartphone inherits functionality from both Camera and Phone.

8. Method Overriding

A child class can provide its own implementation of a method that already exists in the parent class. This is called method overriding.

Python Code
class Employee:
    def work(self):
        print("Employee is working")


class Developer(Employee):
    def work(self):
        print("Developer is writing code")


class Designer(Employee):
    def work(self):
        print("Designer is creating designs")


developer = Developer()
designer = Designer()

developer.work()
designer.work()
Output:
Developer is writing code
Designer is creating designs
9. Real-Time Example: E-Commerce System

An e-commerce application can use inheritance to create different product types from a common product class.

Python Code
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def show_product(self):
        print("Product:", self.name)
        print("Price:", self.price)


class Electronics(Product):
    def warranty(self):
        print("Warranty: 1 Year")


class Clothing(Product):
    def size(self):
        print("Available sizes: S, M, L, XL")


laptop = Electronics("Laptop", 55000)
shirt = Clothing("T-Shirt", 1200)

laptop.show_product()
laptop.warranty()

shirt.show_product()
shirt.size()
Output:
Product: Laptop
Price: 55000
Warranty: 1 Year
Product: T-Shirt
Price: 1200
Available sizes: S, M, L, XL
10. Real-Time Example: Hospital Management

A hospital system can have a common Person class and specialized classes such as Doctor and Patient.

Python Code
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_person(self):
        print("Name:", self.name)
        print("Age:", self.age)


class Doctor(Person):
    def treat_patient(self):
        print(self.name, "is treating the patient")


class Patient(Person):
    def take_treatment(self):
        print(self.name, "is receiving treatment")


doctor = Doctor("Dr. Mehta", 42)
patient = Patient("Amit", 35)

doctor.show_person()
doctor.treat_patient()

patient.show_person()
patient.take_treatment()
Output:
Name: Dr. Mehta
Age: 42
Dr. Mehta is treating the patient
Name: Amit
Age: 35
Amit is receiving treatment
11. Inheritance with Constructor

When a child class defines its own constructor, the parent constructor is not automatically called. Use super() when the parent initialization is required.

Python Code
class Customer:
    def __init__(self, name):
        self.name = name


class PremiumCustomer(Customer):
    def __init__(self, name, membership):
        super().__init__(name)
        self.membership = membership

    def show_details(self):
        print("Customer:", self.name)
        print("Membership:", self.membership)


customer = PremiumCustomer("Sneha", "Gold")

customer.show_details()
Output:
Customer: Sneha
Membership: Gold
12. Checking Inheritance with isinstance() and issubclass()

Python provides built-in functions to check relationships between classes and objects.

Python Code
class Animal:
    pass


class Dog(Animal):
    pass


dog = Dog()

print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(issubclass(Dog, Animal))
print(issubclass(Dog, object))
Output:
True
True
True
True

isinstance() checks whether an object belongs to a class or its inherited classes, while issubclass() checks the relationship between two classes.

13. Real-Time Example: Online Payment System

Payment systems often share common payment behavior while different payment methods implement their own processing.

Python Code
class Payment:
    def __init__(self, amount):
        self.amount = amount

    def show_amount(self):
        print("Payment Amount:", self.amount)


class CreditCardPayment(Payment):
    def pay(self):
        print("Paid using Credit Card")


class UPIPayment(Payment):
    def pay(self):
        print("Paid using UPI")


card = CreditCardPayment(2500)
upi = UPIPayment(1500)

card.show_amount()
card.pay()

upi.show_amount()
upi.pay()
Output:
Payment Amount: 2500
Paid using Credit Card
Payment Amount: 1500
Paid using UPI
14. Real-Time Example: Food Delivery System

A food delivery application can have a common DeliveryPartner class. Different delivery partners can inherit common information and add their own delivery behavior.

Python Code
class DeliveryPartner:
    def __init__(self, name, partner_id):
        self.name = name
        self.partner_id = partner_id

    def show_details(self):
        print("Partner:", self.name)
        print("ID:", self.partner_id)


class BikeDelivery(DeliveryPartner):
    def deliver(self):
        print(self.name, "is delivering by bike")


class CarDelivery(DeliveryPartner):
    def deliver(self):
        print(self.name, "is delivering by car")


bike = BikeDelivery("Ravi", "D101")
car = CarDelivery("Arjun", "D102")

bike.show_details()
bike.deliver()

car.show_details()
car.deliver()
Output:
Partner: Ravi
ID: D101
Ravi is delivering by bike
Partner: Arjun
ID: D102
Arjun is delivering by car
15. Types of Inheritance in Python
Type Description Example
Single One child inherits from one parent. Animal → Dog
Multilevel A class inherits through multiple levels. Grandparent → Parent → Child
Multiple One child inherits from multiple parents. Camera + Phone → Smartphone
Hierarchical Multiple children inherit from one parent. Vehicle → Car, Bike
Hybrid A combination of different inheritance types. Combination of multiple patterns
Note: Python supports all these inheritance patterns through class definitions.
16. Complete Real-Time Example: Company Management

This example combines inheritance, constructors, super(), and method overriding in a small company management system.

Python Code
class Employee:
    def __init__(self, name, employee_id, salary):
        self.name = name
        self.employee_id = employee_id
        self.salary = salary

    def show_details(self):
        print("Name:", self.name)
        print("Employee ID:", self.employee_id)
        print("Salary:", self.salary)

    def work(self):
        print(self.name, "is working")


class Developer(Employee):
    def __init__(self, name, employee_id, salary, language):
        super().__init__(name, employee_id, salary)
        self.language = language

    def work(self):
        print(self.name, "is developing using", self.language)

    def show_role(self):
        print("Role: Developer")


class Manager(Employee):
    def __init__(self, name, employee_id, salary, team_size):
        super().__init__(name, employee_id, salary)
        self.team_size = team_size

    def work(self):
        print(self.name, "is managing the team")

    def show_role(self):
        print("Role: Manager")
        print("Team Size:", self.team_size)


developer = Developer(
    "Rahul",
    "DEV101",
    65000,
    "Python"
)

manager = Manager(
    "Priya",
    "MGR101",
    90000,
    10
)

developer.show_details()
developer.show_role()
developer.work()

print()

manager.show_details()
manager.show_role()
manager.work()
Output:
Name: Rahul
Employee ID: DEV101
Salary: 65000
Role: Developer
Rahul is developing using Python

Name: Priya
Employee ID: MGR101
Salary: 90000
Role: Manager
Team Size: 10
Priya is managing the team

This demonstrates how a parent class can contain common employee functionality while child classes provide specialized behavior.

17. Important Inheritance Rules

Rule 1: Child classes inherit parent methods

A child object can normally access methods defined in its parent class.

Rule 2: Child classes can add new methods

A child class can extend the functionality of its parent by defining additional methods.

Rule 3: Child classes can override methods

A child can replace a parent's method implementation with its own implementation.

Rule 4: Use super() for parent functionality

super() is commonly used to call parent methods, especially the parent constructor.

Rule 5: Inheritance promotes code reuse

Common functionality can be written once in the parent class and reused by multiple child classes.

Remember: Inheritance represents an "is-a" relationship. For example, a Car is a Vehicle and a Developer is an Employee.

Python Inheritance - Real-Time Examples

Learn once. Reuse everywhere. Build better Python applications.