Inheritance in Python

Getting your Trinity Audio player ready...

Object-Oriented Programming (OOP) in Python allows developers to write clean, reusable, and maintainable code. One of its most powerful features is Inheritance — a mechanism that lets one class acquire properties and behaviors (methods and attributes) from another class.

Inheritance in Python

In this guide, you’ll learn what inheritance is, how it works, its types, and how to implement Inheritance in Python with clear examples.


What is Inheritance in Python?

Inheritance means creating a new class (child/subclass) from an existing class (parent/superclass).
The child class inherits the attributes and methods of the parent class, allowing you to reuse code without rewriting it.

Syntax:

class ParentClass:
    # parent class code

class ChildClass(ParentClass):
    # child class code

Example 1: Basic Inheritance

class Animal:
    def speak(self):
        print("Animal makes a sound")

# Dog class inherits from Animal
class Dog(Animal):
    def bark(self):
        print("Dog barks")

# Object of Dog
d = Dog()
d.speak()  # Inherited method
d.bark()   # Child class method

Output:

Animal makes a sound
Dog barks

Here, the Dog class inherits the speak() method from the Animal class.


Why Use Inheritance?

  1. Code Reusability: Avoid rewriting the same code.
  2. Extensibility: Easily extend existing functionality.
  3. Maintainability: Makes code cleaner and easier to update.
  4. Organization: Keeps your code structured and logical.

Example 2: Using __init__() in Inheritance

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

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)  # Call parent constructor
        self.student_id = student_id

    def show(self):
        print(f"Name: {self.name}, Age: {self.age}, ID: {self.student_id}")

s = Student("Riya", 21, "ST123")
s.show()

Output:

Name: Riya, Age: 21, ID: ST123

Here, super().__init__() helps call the parent class constructor.


The super() Function

super() is used to call a method of the parent class without explicitly naming it.
It’s most commonly used inside the __init__() method.

Example:

super().method_name()

This is useful for maintaining cleaner, modular code and especially when using multiple inheritance.


Types of Inheritance in Python

Python supports five types of inheritance:

TypeDescriptionExample
Single InheritanceChild inherits from one parent classclass B(A)
Multiple InheritanceChild inherits from more than one parentclass C(A, B)
Multilevel InheritanceChain of inheritanceclass C(B) where B(A)
Hierarchical InheritanceMultiple child classes inherit from one parentclass B(A), class C(A)
Hybrid InheritanceCombination of two or more inheritance typesMix of above types

Example 3: Single Inheritance

class Vehicle:
    def info(self):
        print("This is a vehicle")

class Car(Vehicle):
    def start(self):
        print("Car started")

obj = Car()
obj.info()
obj.start()

✅ Output:

This is a vehicle
Car started

Example 4: Multiple Inheritance

class Engine:
    def engine_info(self):
        print("Engine: V8")

class Body:
    def body_info(self):
        print("Body: Sedan")

class Car(Engine, Body):
    def car_info(self):
        print("Car: Mustang")

c = Car()
c.engine_info()
c.body_info()
c.car_info()

✅ Output:

Engine: V8
Body: Sedan
Car: Mustang

Python uses Method Resolution Order (MRO) to decide which parent’s method runs first in multiple inheritance.


Example 5: Multilevel Inheritance

class GrandParent:
    def feature1(self):
        print("Feature 1 from GrandParent")

class Parent(GrandParent):
    def feature2(self):
        print("Feature 2 from Parent")

class Child(Parent):
    def feature3(self):
        print("Feature 3 from Child")

c = Child()
c.feature1()
c.feature2()
c.feature3()

✅ Output:

Feature 1 from GrandParent
Feature 2 from Parent
Feature 3 from Child

Example 6: Hierarchical Inheritance

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Dog barks")

class Cat(Animal):
    def meow(self):
        print("Cat meows")

d = Dog()
c = Cat()

d.speak()
c.speak()

✅ Output:

Animal speaks
Animal speaks

Example 7: Hybrid Inheritance

class A:
    def methodA(self):
        print("Method A")

class B(A):
    def methodB(self):
        print("Method B")

class C(A):
    def methodC(self):
        print("Method C")

class D(B, C):
    def methodD(self):
        print("Method D")

d = D()
d.methodA()

✅ Output:

Method A

Method Resolution Order (MRO)

When multiple inheritance is used, Python determines which method to call first using MRO.
You can check it using:

print(D.mro())

✅ Example output:

[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]

Key Takeaways

  • Inheritance allows code reuse and logical hierarchy.
  • Use super() to call parent class methods.
  • Python supports single, multiple, multilevel, hierarchical, and hybrid inheritance.
  • MRO decides the method call order in multiple inheritance.
  • Inheritance makes your code cleaner, modular, and extensible.

Real-Life Analogy

Think of inheritance like a family tree:

  • A Parent class defines general traits (like name, age).
  • A Child class inherits them and adds its own traits (like student_id, marks).

This makes code more organized and realistic — just like real-world relationships.


Practice Challenge

Try creating a simple class structure:

  • Employee (base class)
  • Manager and Developer (derived classes)
  • Add common methods like show_details() and specific ones like assign_task() or write_code().

Conclusion

Inheritance is the foundation of Object-Oriented Programming in Python.
It simplifies complex systems by allowing you to build on top of existing code rather than starting from scratch.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top