What is Inheritance ?

Inheritance is an Object-Oriented Programming (OOP) concept where one class acquires the properties and methods of another class.

  • The class that gives properties → Parent / Base class

  • The class that receives properties → Child / Derived class


Syntax :
Python
class ChildClass(ParentClass): statements 
Example :
Python
class Animal: def speak(self): print("Animal makes a sound") class Dog(Animal): pass d = Dog() d.speak() #output Animal makes a sound
Dog inherits the speak() method from Animal

Accessing Parents Class Methods :
Python
class Vehicle: def start(self): print("Vehicle started") class Car(Vehicle): def drive(self): print("Car is driving") c = Car() c.start() c.drive() 

__init__( ) in Inheritance :
If the child class has its own constructor, the parent constructor is not called automatically.
Python
class Person: def __init__(self, name): self.name = name class Student(Person): def __init__(self, name, roll): self.roll = roll s = Student("Rahul", 101) #output Throws Error

Using super( ) Function :
The super( ) function is used to call the parent class constructor or methods.
Python
class Person: def __init__(self, name): self.name = name class Student(Person): def __init__(self, name, roll): super().__init__(name) self.roll = roll s = Student("Rahul", 101) print(s.name, s.roll) #output Rahul 101
Types of Inheritance :
Single Inheritance :
One child inherits from one parent.
Python
class Parent: pass class Child(Parent): pass 
Multilevel Inheritance :
Inheritance across multiple levels
Python
class Grandparent: pass class Parent(Grandparent): pass class Child(Parent): pass 
Multiple Inheritance :
One child inherits from multiple parents. 
Python
class Father: def skill1(self): print("Driving") class Mother: def skill2(self): print("Cooking") class Child(Father, Mother): pass c = Child() c.skill1() c.skill2() 

Hierarchical Inheritance :
Multiple children inherit from one parent.
Python
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass 

Method Overriding in Inheritance :
One child inherits from multiple parents.
Python
class Father: def skill1(self): print("Driving") class Mother: def skill2(self): print("Cooking") class Child(Father, Mother): pass c = Child() c.skill1() c.skill2()