Python Inheritance – Reuse Code Like a Pro

Last updated 5 months, 1 week ago | 369 views 75     5

Tags:- Python

Inheritance is one of the core concepts of Object-Oriented Programming (OOP) in Python. It allows you to define a new class that inherits properties and methods from an existing class. This promotes code reuse, modularity, and hierarchy in your program.


What is Inheritance?

Inheritance allows one class (called the child class or subclass) to inherit the attributes and methods of another class (called the parent class or base class).

Why Use Inheritance?

  • Reuse existing code

  • Add or override features in the child class

  • Build hierarchies of classes

  • Promote cleaner and DRY (Don't Repeat Yourself) code


Syntax of Inheritance

class Parent:
    # parent class code

class Child(Parent):
    # child class code

✅ Basic Example

class Animal:
    def speak(self):
        print("I am an animal")

class Dog(Animal):
    def bark(self):
        print("Woof!")
d = Dog()
d.speak()  # Inherited from Animal
d.bark()   # Defined in Dog

Overriding Methods

A child class can override methods of the parent class.

class Animal:
    def speak(self):
        print("Generic animal sound")

class Cat(Animal):
    def speak(self):
        print("Meow!")
c = Cat()
c.speak()  # Meow!

Using super() to Call Parent Methods

The super() function is used to call a method from the parent class.

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

    def speak(self):
        print("Animal sound")

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Call parent constructor
        self.breed = breed

    def speak(self):
        super().speak()  # Call parent method
        print("Woof!")
d = Dog("Buddy", "Labrador")
d.speak()

Output:

Animal sound
Woof!

Types of Inheritance in Python

Type Description Example
Single Inheritance Child inherits from one parent class B(A)
Multiple Inheritance Child inherits from more than one parent class C(A, B)
Multilevel Inheritance Inheritance chain: A → B → C class C(B) where B(A)
Hierarchical Inheritance Multiple children from a single parent class B(A), class C(A)

Multiple Inheritance Example

class Father:
    def skills(self):
        print("Gardening, Driving")

class Mother:
    def skills(self):
        print("Cooking, Teaching")

class Child(Father, Mother):
    def skills(self):
        super().skills()  # Uses first parent in MRO
        print("Python Programming")

c = Child()
c.skills()

Output:

Gardening, Driving
Python Programming

Note: Python uses Method Resolution Order (MRO) to decide the order in which base classes are searched.


Multilevel Inheritance Example

class Grandparent:
    def house(self):
        print("Big house")

class Parent(Grandparent):
    def car(self):
        print("BMW")

class Child(Parent):
    def bike(self):
        print("Yamaha")

c = Child()
c.house()  # Inherited from Grandparent
c.car()    # Inherited from Parent
c.bike()   # Defined in Child

Practical Example: Employee Management System

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

    def show(self):
        print(f"Name: {self.name}, Salary: {self.salary}")

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

    def show(self):
        super().show()
        print(f"Department: {self.department}")
m = Manager("Alice", 90000, "IT")
m.show()

Output:

Name: Alice, Salary: 90000
Department: IT

⚠️ Common Pitfalls

Pitfall Description Fix
Forgetting super() in subclass Parent attributes not initialized Always call super().__init__()
Name collision Child method overrides parent unintentionally Be careful when naming methods
Multiple inheritance confusion Method Resolution Order can be complex Use mro() to inspect class hierarchy
print(Child.mro())

Tips and Best Practices

  • ✅ Use inheritance only when there’s a clear “is-a” relationship

  • ✅ Prefer composition over inheritance when possible

  • ✅ Keep class hierarchies simple and intuitive

  • ✅ Use super() to enhance base methods, not replace them blindly

  • ✅ Document overridden methods clearly


Summary Table

Term Description
class Child(Parent) Creates a subclass
super() Calls method from parent class
__init__() Constructor, used to initialize attributes
mro() Method Resolution Order of classes

Final Challenge: Build Your Own System

Try building a class hierarchy like this:

Vehicle (base)
 ├── Car
 │    └── ElectricCar
 └── Bike

Add features like speed, fuel_type, and override methods such as start() and stop() in child classes.