Inheritance

What is Inheritance?

Inheritance is one of the prime features of Object-Oriented Programming (OOP) in Python and other programming languages. It allows a class (known as the child or derived class) to inherit the attributes and methods of another class (known as the parent or base class). The main advantage of this mechanism is code reusability and the ability to add more features to a class without modifying it.

How Does Inheritance Work?

Let’s understand how inheritance works through an example:

Imagine you have a class called Vehicle with basic attributes like color, brand, and speed.

1class Vehicle:
2    def __init__(self, color, brand, speed):
3        self.color = color
4        self.brand = brand
5        self.speed = speed
6
7    def move(self):
8        print("The vehicle is moving")

Now, you want to create a new class, Car, which has all the features of Vehicle and additional ones. Here is where inheritance comes into play.

1class Car(Vehicle):
2    def __init__(self, color, brand, speed, engine_type):
3        super().__init__(color, brand, speed)
4        self.engine_type = engine_type
5        
6    def move(self):
7        super().move()
8        print("The car is moving")

In this example:

  • Car is the child class (derived class) and Vehicle is the parent class (base class).
  • Car inherits attributes (color, brand, speed) and methods (move) from Vehicle.
  • super().__init__(color, brand, speed) is used to call the constructor of the parent class.
  • We have extended the Car class by adding a new attribute (engine_type)
  • We have overridden the move method in the Car class to add more details. However, we called the parent’s move method using super().move()

Note

The super() function in Python is used to call a method in the parent class from the child class.

This way, you can re-use code efficiently, building complex systems with components that share common features, and easily extend your classes.

Types of Inheritance

In Python, there are mainly four types of inheritances:

  1. Single Inheritance: When a child class inherits from a single parent class.
  2. Multiple Inheritance: When a child class inherits from more than one parent class.
  3. Multi-Level Inheritance: When a child class inherits from a parent class, and then another class inherits from that child class.
  4. Hierarchical Inheritance: When one class is inherited by more than one child class.

Remember, Inheritance can effectively help you to reuse code and implement real-world relationships in your programs, but they should be used judiciously to avoid complexity.