Inheritance

Inheritance allows you to create a new class that is a modified version of an existing class, inheriting the attributes and methods of the parent class (also known as the base or superclass).

Example

All the data members and member functions of the parent class are inherited by child class. It means that they are also members of child class and we can access them using object of child class.

All animals can sleep, therefore sleep method is present in parent class. But lion eats meat and zebra eats grass. Therefore these methods are separately defined in their respective classes. Now, we can access sleep method using objects of both child classes but eat method can be accessed only by objects of respective classes.

__init__() in inheritance

When we inherit a child class from a parent class, we can use the __init__() function of parent class to initialize data members of child class. This is called overriding.

super() function

In Python, the super() function is used to call a method from a parent or superclass within a child class. It allows you to access and invoke methods and constructors of the parent class, enabling you to extend and customize the behavior of the parent class's methods in the child class.

Levels of Inheritance

The three levels of inheritance in Python are as follows:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance

Single Inheritance

Single inheritance is the simplest form of inheritance in Python. In this form, a class can inherit from only one parent class.

Multiple Inheritance

Multiple inheritance occurs when a class inherits from more than one parent class. In this case, the child class can inherit attributes and methods from multiple parent classes.

Multilevel Inheritance

Multilevel inheritance occurs when a class inherits from another class, which in turn inherits from another class. In other words, it forms a chain of inheritance. This allows you to create a hierarchy of classes.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

Which of the following is a best practice in programming?

10 XP~2 min
Exercise 2 of 2Easy

Code that is easy to read and understand is called ___ code.

10 XP~2 min