Inheritance in Python with Example

Inheritance is a powerful object-oriented programming feature offered by Python. This powerful feature allows to one class to inherit the properties and behaviors of another class.

For example, some classes can have common members like fields / variables or methods / functions. Instead of defining the same members for every class, common members are put in a class and other classes used them without defining again. This is called inheritance.

In Python or other programming languages like C++ or Java, inheritance is a technique for organizing information in a hierarchical form.

It offers a reusability mechanism in object-oriented programming (OOP) for programmers to reuse the existing code within the new applications. Thereby, the programmer can reduce the code duplication.

The main purpose of implementing inheritance feature is to reuse the existing code in a new class. We do this by building a relationship between a new class and an existing class and define a new code in terms of existing code. This relationship is known as parent-child relationship in Python.

In this tutorial, we will understand the basic concept of inheritance in Python with real-time example, syntax of creating subclasses, uses, and advantages.

What is Inheritance in Python OOPs?


The technique of creating a new class based on the functionality of an existing class is called inheritance in Python. In other words, inheritance is a process by which a subclass acquires all the properties (i.e. attributes) and behaviors (i.e. methods) of the superclass.

Let’s understand the basic meaning of inheritance with the help of real-time example. In the real world, a child inherits the features of its parents, such as the beauty of mother and the intelligence of the father. Thus, inheritance in Python is a way to model the “is-a or parent-child” relationship between objects.

Superclass: The superclass is the existing class from where attributes and methods are inherited. In other words, the class which have common members is called base class, superclass, or parent class. It acts as a template for creating subclasses. It contains common properties and behaviors that can be shared among multiple subclasses.

Subclass: The subclass is the new class that is created based on the superclass. In other words, a class which takes common members from another class is called subclass. It is also called child class, derived class, or extended class.

When a class is created through inheritance, it inherits attributes and methods defined by the superclass. However, a subclass can also add its own unique attributes and methods as well. The superclass remains unchanged.

Syntax to Create Subclass in Python


To create a subclass in Python, we use the class keyword, followed by the name of the subclass and the name of the superclass in parentheses. The general syntax for creating a subclass is as follows:

class subclass_name(superclass_name):
     # Subclass body

In the above syntax, the subclass inherits a superclass in Python by simply specifying the superclass in parentheses [( )] after the subclass name. Inheritance developed in Python when we specify the name of superclass in the parentheses.

Once the relationship is done, the code is automatically reusable. When we create a subclass, no memory is allocated, but memory is allocated when we create an object of the subclass.


Remember that if you want to implement the concept of inheritance, you need to create minimum of two classes in your program and maximum you can create any number of classes. Let’s take an example based on the above syntax.

Example 1:

# Simple inheritance example program in Python.
# Creating a superclass.
class Superclass:
  # Define a method inside the superclass.
    def m1(self):
        print("I am a superclass method.")

# Creating a subclass by specifying the name of superclass in parentheses.
class Subclass(Superclass):
    # Define a new method inside the subclass.
    def m2(self):
        print("I am a subclass method.")

# Outside the class definition.
# Creating an object of superclass.
sc = Superclass()

# Calling the m1() method of superclass using superclass object reference variable.
sc.m1()

# Creating an object of subclass.
sb = Subclass()

# Calling the m1() of superclass using subclass object reference variable.
sb.m1()

# Calling the m1() of superclass using subclass object reference variable.
sb.m2()
Output:
       I am a superclass method.
       I am a superclass method.
       I am a subclass method.

In the above example, there is nothing special in the superclass. It is simply a regular class with a method.

How Features of Superclass are Inherited in Subclass in Python?


Let’s take a simple example program to understand how features of superclass are inherited inside the subclass in Python. Consider the below example as shown in the figure.

How features of superclass are inherited in subclass via inheritance in Python

1. The BaseClass is a superclass of DerivedClass.

2. The DerivedClass is a subclass of BaseClass, meaning that a DerivedClass extends the BaseClass. The arrow in the figure expresses the concept of derivation. The direction from the DerivedClass towards the BaseClass represents that the DerivedClass has all the features of the BaseClass but not vice versa.

3. The features() method of the BaseClass is inherited in the DerivedClass. In addition to it, the DerivedClass adds its own specific ownFeature() method. Look at the following program code to understand better.

Example 2:

# Creating a superclass.
class BaseClass:
  # Define a method inside the superclass.
    def features(self):
        print("Feature A")
        print("Feature B")

# Creating a subclass by specifying the name of superclass in parentheses.
class DerivedClass(BaseClass):
  # Define a method inside the subclass.
    def ownFeature(self):
        print("Feature C")

# Outside the class definition.
# Creating an object of subclass.
dc = DerivedClass()

# Calling the features() of superclass using subclass object reference variable dc.
dc.features()

# Calling the ownFeature() method of superclass using subclass object reference variable dc.
dc.ownFeature()
Output:
       Feature A
       Feature B
       Feature C

As you can observe in this example, we have not created an object of superclass. Still, a copy of it is available to the subclass. In other words, members of the superclass are available to the subclass.

This is because we developed a relationship between superclass and subclass through inheritance. Due to which the subclass contains the copy of superclass members.

Why do We Need / Use Inheritance in Python?


With the inheritance, we can reuse code from the base class. In other words, we can use the existing feature of a class. Let’s take a simple example program to understand the need or use of inheritance in Python programming. Consider the following program code without using inheritance.

Example 3:

class A:
    def m1(self):
        print("One")

class B:
    def m1(self):
        print("One")

    def m2(self):
        print("Two")

class C:
    def m1(self):
        print("One")

    def m2(self):
        print("Two")

    def m3(self):
        print("Three")

In this example code, we have created three classes named A, B, and C, respectively. The class A contains m1() method, class B contains two methods m1() and m2(), and class C contains three methods m1(), m2(), and m3(). Can you think what are the disadvantages of this code?

There are three disadvantages to this code.

  • First is code duplication.
  • Second is the length of the code.
  • Third is it increases the chances of error.

In this code, we have defined m1() method three times, and m2() method two times. Here, the redundancy of code is code duplication. In the realtime application project, code duplication is not allowed. Due to the duplication, the length of code is also increased. Therefore, we can reduce the length of code by developing a relationship between two classes using the inheritance feature, but how? Let’s understand it.

We will make a relationship between the two classes via inheritance. Once the relationship is done, the code is automatically reusable. Look at the below code.

class A:
    def m1(self):
        print("One")

class B(A):
    def m2(self):
        print("Two")

class C(B):
    def m3(self):
        print("Three")

# Outside the class definition.
# Create an object of class C.
c = C()

# Calling methods using object reference variable c.
c.m1()
c.m2()
c.m3()
Output:
       One
       Two
       Three

As you can observe in this code, we have easily avoided the code duplication as well as reduced the length of code with the help of inheritance feature provided by object-oriented programming in Python.

With inheritance, we have to write methods only one time instead of many times. The m1() method of class A automatically comes in class B, m1() and m2() methods of class B come in class C. We have created an instance of class C and calls all the methods available in it using object reference variable c.

This is the main advantage of using inheritance feature offered Python OOPs. Hope that you will have understood when to use inheritance concept in the Python programming.

Access to Superclass Members in Python


Python provides a built-in super() function which we can use to access the attributes and methods of the superclass. The main advantage of using this super() function is that we do not need to define the name of superclass at the time of calling. The following example code below shows the use case of super() function.

Example 4:

# Python program to demonstrate the use of super() function in place of class name
class Vehicle:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

    def display_info(self):
        return f"Brand: {self.brand}, Model: {self.model}"

class Car(Vehicle):
    def __init__(self, brand, model, fuel_type):
      # Use of super() function in place of class name.
        super().__init__(brand, model)
        self.fuel_type = fuel_type

    def display_info(self):  # Method override
      # Use of super() function to call superclass display_info() method
        base_info = super().display_info()
        return f"{base_info}, Fuel Type: {self.fuel_type}"

# Outside the class definition.
# Creating instances of the subclasses
vehicle = Vehicle("Generic", "Basic")
car = Car("Toyota", "Camry", "Gasoline")

# Calling methods of the subclass.
print(vehicle.display_info())
print(car.display_info())
Output:
       Brand: Generic, Model: Basic
       Brand: Toyota, Model: Camry, Fuel Type: Gasoline

In this example, Vehicle is the superclass, and Car is the subclass. Car inherits the brand and model attributes from Vehicle and has its own attribute, fuel_type. Inside the Car subclass, we have called __init__() method of Vehicle superclass using super() function to set the “brand and model” attributes. The display_info method is overridden in the Car class to include the fuel_type information.

Example 5:

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"{self.name} makes a sound")

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed

    def speak(self):
        # Call the speak method of the superclass (Animal)
        super().speak()
        print(f"{self.name} ({self.breed}) barks")

# Creating an instance of the subclass Dog.
dog = Dog("Buddy", "Golden Retriever")

# Calling the speak() method of the Dog class.
dog.speak()
Output:
       Buddy makes a sound
       Buddy (Golden Retriever) barks

In this example, we have a superclass Animal with an __init__() method to initialize the name attribute and a speak() method that will print a generic message. The Dog class is a subclass of Animal. It also has an __init__() method in which we have used super() function to initialize the name attribute, and self parameter to set an additional breed attribute.

The speak method is overridden in the Dog class to include the breed attribute and to call the speak method of the superclass using super(). Then, we have created an instance of the Dog class by passing argument values as “Buddy” and “Golden Retriever.”

When we call the speak() method on the dog object, it first calls the speak() method of the Dog class, which, in turn, calls the speak() method of the Animal class using super() function. This allows us to extend the behavior of the speak() method while still utilizing the original behavior of the Animal class.

Use of issubclass() Function in Inheritance


Python provides a built-in issubclass() method to check the relationships between the specified classes. This method returns true if the first class is a subclass of the second class. Otherwise, it returns false. The general syntax for using issubclass() is as follows:

issubclass(subclass_name, superclass_name)

Let’s take an example based on this syntax.

Example 6:

class Vehicle:
    pass

class Car(Vehicle):
    pass

# Check if Car is a subclass of Vehicle
result1 = issubclass(Car, Vehicle)

# Check if Vehicle is a subclass of Car (which it is not).
result2 = issubclass(Vehicle, Car)

print(result1)
print(result2)
Output:
       True
       False

In this example, Car is a subclass of the Vehicle class, so the statement issubclass(Car, Vehicle) return True. However, Vehicle is not a subclass of Car, so the statement issubclass(Vehicle, Car) returns False.

The issubclass() method is useful when you need to dynamically determine class relationships, especially when working with large class hierarchies.

Types of Inheritance in Python


Like C++ or Java, Python also supports different types of inheritance. Depending on the number of subclass and superclass involved, there are five types of inheritance in Python that are as:

  • Single inheritance
  • Multilevel inheritance
  • Multiple inheritance
  • Hierarchical inheritance
  • Hybrid inheritance

We understand types of inheritance one by one in the next tutorial with the help of examples.

Advantage of Inheritance in Python Programming


Inheritance in Python provides several advantages that make it a powerful and fundamental feature of object-oriented programming. Some of the key advantages of using inheritance in Python programming are as follows:

(1) Inheritance allows us to reuse code from an existing class (the superclass) in a new class (the subclass). Using inheritance, we can increase code reusability and readability by putting the common code into the superclass and sharing amongst several subclasses.

(2) With inheritance, we can minimize the length of the duplicate code in an application.

(3) Due to reducing the length of code, redundancy of the application is also reduced.

(4) Inheritance helps in organizing and structuring our codebase. We can create a hierarchy of classes, starting with a superclass that defines common attributes and methods, and then create more subclasses with additional or overridden methods. This systematic approach simplifies code maintenance and updates.

(5) Inheritance reduces memory usage because we don’t need to write the same code for each subclass.

(6) Subclasses can override or extend the behavior of the superclass. This allows us to modify the functionality to meet specific requirements while retaining the common features from the superclass.

(7) By dividing the code into multiple classes, we can easily identity bugs in an application.

(8) Inheritance simplifies code debugging in Python because we can focus on specific parts of the code hierarchy. If there’s an issue with a method in the superclass, fixing it there will benefit all subclasses.


In this tutorial, we have discussed inheritance in Python with the help of various example programs. Hope that you will have understood the basic concepts of inheritance and enjoyed tutorial.
Thanks for reading!!!

Please share your love