Nearby lessons

107 of 159

Python - Inheritance

📌 What You Will Learn
  • Understand the concept of inheritance
  • Know the different types of inheritance
  • Use super() to call parent class methods
  • Implement method overriding in a child class
  • Implement constructor overriding and call super().__init__()

What is Inheritance?

Inheritance is one of the fundamental concepts of Object-Oriented Programming.

Whatever members are available in the Parent Class (also called Base or Super Class) are automatically available to the Child Class (also called Derived or Sub Class).

This concept of reusing the parent class members in the child class is called Inheritance.

Why Do We Need Inheritance?

  • Code reuse: existing code can be used again in a child class.
  • Reduces code duplication.
  • Improves code maintainability.
  • Represents real-world relationships (a child is a parent).

Syntax

🐍Code Cell
1class Parent:
2 # parent class members
3 
4 
5class Child(Parent):
6 # child class inherits Parent members
Output
No output captured.

Explanation

The child class is defined by placing the parent class name inside parentheses:

🐍Code Cell
1class Child(Parent):
Output
No output captured.

Types of Inheritance

Python supports several types of inheritance.

Type Description
Single Inheritance One child class inherits from one parent class.
Multilevel Inheritance A class is inherited from another derived class.
Hierarchical Inheritance Multiple child classes inherit from one parent class.
Multiple Inheritance One child class inherits from more than one parent class.

Example of Single Inheritance

🐍Code Cell
1class Animal:
2 
3 def eat(self):
4 print("Animal eats food")
5 
6 
7class Dog(Animal):
8 
9 def bark(self):
10 print("Dog barks")
11 
12 
13d = Dog()
14 
15d.eat()
16d.bark()
Output
Animal eats food
Dog barks

Explanation

Here, Dog inherits from Animal. Because of inheritance, the Dog object can call the eat() method defined in the parent class.

What is Method Overriding?

Whatever members are available in the Parent Class are automatically available to the Child Class through inheritance.

Sometimes, the child class may not be satisfied with the implementation provided by the parent class.

In that situation, the child class can redefine the same method according to its own requirement.

This concept is called Method Overriding.

When a child class provides its own implementation of a method that is already available in the parent class, it is called Method Overriding.

The overriding concept is applicable to both:

  • Methods
  • Constructors

Demo Program for Method Overriding

🐍Code Cell
1class P:
2 
3 def property(self):
4 print('Gold+Land+Cash+Power')
5 
6 def marry(self):
7 print('Appalamma')
8 
9 
10class C(P):
11 
12 def marry(self):
13 print('Katrina Kaif')
14 
15 
16c = C()
17 
18c.property()
19c.marry()
Output
Gold+Land+Cash+Power
Katrina Kaif

Explanation

  • The child class C inherits both property() and marry() from P.
  • property() is not overridden, so the parent implementation executes: Gold+Land+Cash+Power.
  • marry() is overridden in the child class, so the child implementation executes: Katrina Kaif.

Calling a Parent Class Method from the Overriding Method

Normally, after overriding a method, calling that method through the child object executes the child implementation.

But sometimes we want to execute both the parent class implementation and the child class implementation.

For this purpose, we can use super().

From the overriding method of the child class, we can call the parent class method by using:

🐍Code Cell
1super().methodName()
Output
No output captured.

What is super()?

super() provides a way to delegate method calls according to Python's method resolution order.

In this simple single-inheritance example, it allows the child class to call the corresponding parent class implementation.

Syntax:

🐍Code Cell
1super().methodName()
Output
No output captured.

Demo Program Using super()

🐍Code Cell
1class P:
2 
3 def property(self):
4 print('Gold+Land+Cash+Power')
5 
6 def marry(self):
7 print('Appalamma')
8 
9 
10class C(P):
11 
12 def marry(self):
13 super().marry()
14 print('Katrina Kaif')
15 
16 
17c = C()
18 
19c.property()
20c.marry()
Output
Gold+Land+Cash+Power
Appalamma
Katrina Kaif

Explanation

  • c.property(): not overridden, so the parent implementation prints Gold+Land+Cash+Power.
  • c.marry(): the child method starts, super().marry() calls the parent implementation first, printing Appalamma.
  • Execution returns to the child method, which prints Katrina Kaif.

How super() Changes the Behaviour

Child marry() Implementation Output of c.marry()
def marry(self):
    print('Katrina Kaif')
                
Katrina Kaif
                
def marry(self):
    super().marry()
    print('Katrina Kaif')
                
Appalamma
Katrina Kaif
                

Without super(), only the child implementation executes. With super().marry(), the inherited implementation is called first and then the remaining child code executes.

What is Constructor Overriding?

The overriding concept is applicable not only to normal methods but also to constructors.

If a child class defines its own __init__() constructor, then that constructor is used when creating objects of the child class.

This concept is called Constructor Overriding.

If the child class defines its own constructor, the parent class constructor is not executed automatically.

Demo Program for Constructor Overriding

🐍Code Cell
1class P:
2 
3 def __init__(self):
4 print('Parent Constructor')
5 
6 
7class C(P):
8 
9 def __init__(self):
10 print('Child Constructor')
11 
12 
13c = C()
Output
Child Constructor

Explanation

When the child object is created, Python finds __init__() in class C, so the child constructor executes.

The parent constructor is not executed automatically.

If the child class does not define a constructor, the parent class constructor is inherited and executes.

Calling the Parent Class Constructor Using super()

If we want to execute the parent class constructor from the child class constructor, we can use super().

🐍Code Cell
1super().__init__()
Output
No output captured.

Demo Program Using super().__init__()

🐍Code Cell
1class P:
2 
3 def __init__(self):
4 print('Parent Constructor')
5 
6 
7class C(P):
8 
9 def __init__(self):
10 super().__init__()
11 print('Child Constructor')
12 
13 
14c = C()
Output
Parent Constructor
Child Constructor

Explanation

  • Inside the child constructor, super().__init__() calls the parent constructor first, printing Parent Constructor.
  • Control returns to the child constructor, which prints Child Constructor.

Without super().__init__() vs With super().__init__()

Situation Child Constructor Output
Without super().__init__()
def __init__(self):
    print('Child Constructor')
                
Child Constructor
                
With super().__init__()
def __init__(self):
    super().__init__()
    print('Child Constructor')
                
Parent Constructor
Child Constructor
                

Complete Program: Reusing the Parent Constructor

This program shows the most common use of super().__init__(): the child class constructor reuses the parent constructor to initialize inherited data, then initializes its own data.

🐍Code Cell
1class Person:
2 
3 def __init__(self, name, age):
4 self.name = name
5 self.age = age
6 
7 
8class Employee(Person):
9 
10 def __init__(self, name, age, eno, esal):
11 super().__init__(name, age)
12 self.eno = eno
13 self.esal = esal
14 
15 def display(self):
16 print('Employee Name :', self.name)
17 print('Employee Age :', self.age)
18 print('Employee Number:', self.eno)
19 print('Employee Salary:', self.esal)
20 
21 
22e1 = Employee('Durga', 48, 872425, 26000)
23e1.display()
24 
25e2 = Employee('Sunny', 39, 872426, 36000)
26e2.display()
Output
Employee Name  : Durga
Employee Age   : 48
Employee Number: 872425
Employee Salary: 26000
Employee Name  : Sunny
Employee Age   : 39
Employee Number: 872426
Employee Salary: 36000

Explanation

  • super().__init__(name, age) calls the parent constructor, which initializes self.name and self.age.
  • The child constructor then initializes the child-specific variables self.eno and self.esal.
  • Without super().__init__(), name and age would never be initialized, and display() would raise an AttributeError.

Method Overriding vs Constructor Overriding

Feature Method Overriding Constructor Overriding
What is Redefined? Normal inherited method __init__()
Inheritance Required Yes Yes
Child Provides Own Implementation Yes Yes
Inherited Implementation Executes Automatically? No, when the overridden method is called No, when child defines its own constructor
Call Inherited Implementation super().method() super().__init__()
Main Purpose Customize inherited behaviour Customize child-object initialization
📝 Key Takeaways
  • Inheritance allows a child class to reuse the members of a parent class
  • The child class inherits all accessible members of the parent class
  • Method overriding lets a child redefine an inherited method
  • super() calls a parent class method or constructor from a child class
  • The parent class constructor is not called automatically when the child defines its own

🧠 Test Your Knowledge

10 Questions
Progress: 0 / 10