Inheritance is an Object-Oriented Programming (OOP) concept that allows a class to inherit attributes and methods from another class.
It helps in code reusability, extensibility, and creating a hierarchical relationship between classes.
The class that inherits is called the child class (derived class),
and the class being inherited from is called the parent class (base class).
🔹 Syntax
class ParentClass:
# parent class code
pass
class ChildClass(ParentClass):
# child class code (inherits ParentClass)
pass🔹 Types of Inheritance in Python
| Type | Description | Example |
|---|---|---|
| Single Inheritance | One child class inherits from one parent class. | class B(A) |
| Multiple Inheritance | A child class inherits from multiple parent classes. | class C(A, B) |
| Multilevel Inheritance | A child class inherits from a parent, which itself inherits another parent. | A → B → C |
| Hierarchical Inheritance | Multiple child classes inherit from a single parent class. | B(A), C(A) |
| Hybrid Inheritance | Combination of multiple types of inheritance. | Mix of above types |
🧩 Example 1: Single Inheritance
class Parent:
def show_parent(self):
print("This is the Parent class")
class Child(Parent):
def show_child(self):
print("This is the Child class")
obj = Child()
obj.show_parent()
obj.show_child()Output:
This is the Parent class
This is the Child class🧩 Example 2: Multilevel Inheritance
class GrandParent:
def show_gp(self):
print("This is the GrandParent class")
class Parent(GrandParent):
def show_parent(self):
print("This is the Parent class")
class Child(Parent):
def show_child(self):
print("This is the Child class")
obj = Child()
obj.show_gp()
obj.show_parent()
obj.show_child()Output:
This is the GrandParent class
This is the Parent class
This is the Child class🧩 Example 3: Multiple Inheritance
class Father:
def skill(self):
print("Father: Driving")
class Mother:
def skill(self):
print("Mother: Cooking")
class Child(Father, Mother):
def show(self):
print("Child: Learning both skills")
obj = Child()
obj.skill() # Executes Father’s skill() because of method resolution order (MRO)
obj.show()Output:
Father: Driving
Child: Learning both skills🧩 Example 4: Using super() to Access Parent Methods
class Parent:
def __init__(self, name):
self.name = name
def show(self):
print(f"Parent Name: {self.name}")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Calls Parent constructor
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
obj = Child("Dheeraj", 24)
obj.show()
obj.display()Output:
Parent Name: Dheeraj
Name: Dheeraj, Age: 24🔹 In Summary
- Inheritance allows a class to reuse and extend functionality of another class.
- Promotes code reusability, organization, and modularity.
super()is used to call parent class methods in the child class.- Supports multiple inheritance, but order of execution is determined by Method Resolution Order (MRO).
