Python OOPS — Inheritance

Sai Prabhanj Turaga
3 min readNov 5, 2023

--

Inheritance is a fundamental concept in object-oriented programming (OOP), including Python. It allows you to define a new class (subclass or derived class) that inherits properties and behaviors (attributes and methods) from an existing class (base class or superclass). This promotes code reusability and the creation of more specialized classes.

Here’s a detailed explanation of Python inheritance with examples

Basic Syntax

In Python, you define a subclass by specifying the base class in parentheses after the subclass name. The subclass inherits all attributes and methods from the base class and can override or extend them.

Example of Inheritance

Let’s create a simple example with a base class Animal and a subclass Dog to demonstrate inheritance:

In this example, Dog is a subclass of Animal. It inherits the __init__ constructor and speak method from the Animal base class. The speak method is overridden in the Dog subclass to provide a specific implementation.

Types of Inheritance

Single Inheritance: A subclass inherits from a single base class.

Multiple Inheritance: A subclass inherits from multiple base classes.

Multilevel Inheritance: A subclass inherits from another subclass.

Method Resolution Order (MRO)

Python follows the C3 Linearization algorithm to determine the Method Resolution Order (MRO) when a class inherits from multiple base classes. The MRO defines the order in which Python looks for methods when they are called on an object.

Using super()

The super() function allows you to call a method from the base class in the subclass, even when the method is overridden.

Inheritance and Encapsulation

Inheritance also inherits the encapsulation principle. Private attributes and methods (those starting with an underscore) in the base class are still accessible from the subclass. However, they should not be accessed directly to maintain encapsulation.

When to Use Inheritance

  • Use inheritance when you want to create a more specialized class based on an existing class.
  • Use inheritance to promote code reusability and avoid duplicating common attributes and methods.

When Not to Use Inheritance

  • Avoid deep inheritance hierarchies, which can make code complex and harder to maintain.
  • In some cases, composition (using objects of other classes) may be a better choice than inheritance.

Inheritance is a powerful OOP concept that allows you to create hierarchies of related classes, promoting code reuse and providing a structured way to model real-world relationships. It’s an essential feature for designing object-oriented Python programs.

--

--

Sai Prabhanj Turaga
Sai Prabhanj Turaga

Written by Sai Prabhanj Turaga

Seasoned Senior Engineer, works with Data

No responses yet