Inheritance is one of the main concepts of Object-Oriented Programming (OOP).
Inheritance allows one class to use the properties and methods of another class.
In simple words:
Inheritance means creating a new class from an existing class.
The existing class is called the Parent Class (Base Class).
The new class is called the Child Class (Derived Class).
Why Use Inheritance?
- Code reuse
- Reduces duplication
- Improves maintainability
- Supports hierarchical structure
Basic Syntax
class Parent:
# parent class codeclass Child(Parent):
# child class code
The child class automatically gets access to the parent class methods and variables.
Simple Example
class Person:
def greet(self):
print("Hello")class Student(Person):
def study(self):
print("Studying")s1 = Student()s1.greet()
s1.study()
Output:
Hello
Studying
Here:
Studentinherits fromPersonStudentcan usegreet()method ofPerson
Using Constructor in Inheritance
If the parent class has a constructor, we can call it using super().
class Person:
def __init__(self, name):
self.name = nameclass Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grades1 = Student("Hira", "A")print(s1.name)
print(s1.grade)
super() calls the parent class constructor.
Types of Inheritance
1. Single Inheritance
One child class inherits from one parent class.
2. Multiple Inheritance
One child class inherits from multiple parent classes.
class Father:
def skill1(self):
print("Gardening")class Mother:
def skill2(self):
print("Cooking")class Child(Father, Mother):
passc1 = Child()
c1.skill1()
c1.skill2()
3. Multilevel Inheritance
A class inherits from a class that already inherited from another class.
4. Hierarchical Inheritance
Multiple child classes inherit from one parent class.
Method Overriding
A child class can redefine a parent method.
class Animal:
def sound(self):
print("Some sound")class Dog(Animal):
def sound(self):
print("Bark")d1 = Dog()
d1.sound()
Output:
Bark
The child method overrides the parent method.
Key Takeaway
Inheritance allows a class to reuse code from another class.
It promotes code reusability, structure, and better organization in OOP programs.