What is Inheritance in Programming?

Inheritance is one of the three main properties of object oriented programming with polymorphism and encapsulation being the other two. Inheritance refers to the ability of a class to inherit methods, properties and attributes from another class. Inheritance fosters code organization and reusability. Like all the other object oriented programming languages, Python supports inheritance. In this article, you will see how to implement inheritance with Python.

Implementing Inheritance in Python

Python supports both single and multiple inheritance. In single inheritance a class is inherited by multiple other classes whereas in multiple inheritance one class can inherit multiple other classes. A class which is inherited by other classes is called base class or parent class. On the other hand, a class that inherits other classes is called a derived class or a child class. This will all make more sense after a couple examples.

Inheriting Multiple Classes from One Class

A Python class can be inherited by multiple classes. In the following script we define a class named Animal. The class contains three methods: set_name(), set_age(), and print_name(). The set_age() method accepts one parameter which initializes the age attribute, whereas set_name() method sets the value of the name attribute. The print_name() method simply prints the value of the name attribute.

class Animal:

    def set_name(self, name):
        self.name = name

    def set_age(self, age):
        self.age = age

    def print_name(self):
        print(self.name)

The idea behind inheritance is that all the attributes that are common between multiple classes are implemented in a single parent class and then all the relevant classes inherit from that parent class. The attributes or methods intrinsic to the invidual classes are implemented in child classes. Since every animal has a name and age, we implemented name and age variables in a parent Animal class.

Let’s now create some dummy child classes for the Animal class.

To inherit the Animal class, you have to define a class and then pass the name Animal in the round brackets that follow the child class name. In the following script, a class Mammal is defined which inherits the Animal class. The Mammal class has two methods: set_kids(), which sets the value of the kids attribute and print_running() which prints a message.

class Mammal(Animal):
    def set_kids(self, num_kids):
        self.kids = num_kids

    def print_running(self):
        print("The", self.name, "is running")

Since one class can be inherited by multiple another classes, let’s create another class, Insect, which inherits the Animal class.

class Insect(Animal):
    def set_eggs(self, num_eggs):
        self.eggs = num_eggs

    def print_flying(self):
        print("The", self.name, "is flying")

We have implemented parent Animal class and two child classes, Mammal and Insect. Let’s now create objects of these classes and see if our Mammal and Insect classes can actually access the attributes and methods of the parent Animal class.

Let’s first create an object of the parent Animal class and access its attributes and methods.

a = Animal()
a.set_name("Lion")
a.set_age(10)
a.print_name()

Output:

Lion

Next we’ll create an object of the Mammal class and call the set_name(), print_name(), and print_running() methods.

m = Mammal()
m.set_name("Monkey")
m.print_name()
m.print_running()

The output below shows that even though the set_name() and print_name() methods are not declared in the Mammal class, they can still be called via the Mammal class object. This is because the Mammal class successfully inherits the Animal class which implements the two methods.

Output:

Monkey
The Monkey is running

In addition to calling the parent class methods, a child class can call its own methods as well. For instance in the following script, the object of the Mammal class is calling the set_kids() method which is defined inside the </mod>Mammal</mod> class.

m.set_kids(10)
print(m.kids)

Output:

10

In the same way, you can create objects of the Insect class and call the parent class methods and attributes via the child class object as shown in the following script.

i = Insect()
i.set_name("Butterfly")
i.print_name()
i.print_flying()

Output:

Butterfly
The Butterfly is flying

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit

Passing Parameters from Child Class to Parent Class Constructor

The instance attributes of a class can be initialized by a constructor which is a method that is automatically called when you create an object of a class. The name of the constructor method is __init__(). For instance in the following script, we modified the Animal class and added a constructor that initializes both the name and age attributes.

class Animal:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def print_name(self):
        print(self.name)

While creating an object of a class, you have to pass the parameter values for the constructor, like we do in this script:

Output:

a = Animal("lion", 10)
a.print_name()
print(a.age)

Now, an important question arise. How can you pass values from the object of a child class to the parent class when a child class object is initialized?

The answer is in the use of the super() keyword, which is used to access the attributes and methods of a parent class inside a child class. Hence, to call a parent class constructor from a child class, you have to use the super() keyword followed by a dot operator and the __init__() method, as shown in the following example.

class Mammal(Animal):
    def __init__(self, name, age, kids):
        super().__init__(name, age)
        self.kids = kids

    def print_running(self):
        print("The", self.name, "is running")

Now when you create the object of the Mammal class, you have to pass the values for the parent class constructor as well as the child class constructor. For instance, in the following script, in the Mammal class constructor, the name and age of the animal are being passed along with the number of kids. Inside the constructor of the Mammal class, the name and age are passed to the Animal class constructor whereas the value for the kids attribute initializes the kid attribute inside the Mammal class constructor. That was a mouthful, but take a look at the following script to see what we mean.

m = Mammal("monkey", "15", 5)
m.print_name()
print(m.age)
m.print_running
print(m.kids)

Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit

Inheriting from an Abstract Class

An abstract class is one which cannot be instantiated. An abstract class serves as a blue print only for the child classes and the child classes have to provide the implementation of all the methods in a parent abstract class.

To create an abstract class, you have to first import the ABC class from the abc module and then import the child class from this ABC class. To declare an abstract method, you have to use the @abstractmethod decorator. An abstract method has no definition. You simply use the keyword pass inside the body of an abstract method. The following script creates an abstract Animal class with an abstract constructor and an abstract method print_name().

from abc import ABC,  abstractmethod

class Animal(ABC):

    @abstractmethod
    def __init__(self, name, age):
        pass

    @abstractmethod    
    def print_name(self):
        print(self.name)

If you try to create an object of the Animal class, you’ll see the following error:

a = Animal()

Output:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-42-2a6156927c44> in <module>
----> 1 a = Animal()

TypeError: Can't instantiate abstract class Animal with abstract methods __init__, print_name

The error clearly tells that the abstract class with abstract methods cannot be instantiated.

In the following, script we create a Mammal class which inherits the abstract class Animal and implements the abstract methods of the Animal class.

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

    def print_name(self):
        print(self.name)

    def print_running(self):
        print("The", self.name, "is running")

Finally, the following script creates an object of the Mammal class and calls the print_name() and print_running() methods.

m = Mammal("tiger", 14, 2)
m.print_name()
m.print_running()

Output:

tiger
The tiger is running

Multiple Inheritance

As we mentioned earlier, a child class in Python can inherit from multiple parent classes. In the following script, we create two parent classes X and Y with methods methodA and methodB respectively. We create another class Z which inherits both the parent classes X and Y.

class X:
    def methodA(self):
        print("This is method A of class X")

class Y:
    def methodB(self):
        print("This is method B of class Y")

class Z(X,Y):
    def methodC(self):
        print("This is method C of child class Z")

In the following script we create an object of the Z class and then call the parent class X’s methodA() and the parent class Y’s methodB() using the child class Z’s object.

z = Z()
z.methodA()
z.methodB()
z.methodC()

The following output confirms that when a class inherits multiple classes, it has access to the methods and attributes of all the parent classes.

Output:

This is method A of class X
This is method B of class Y
This is method C of child class Z

This is a pretty advanced tutorial, so I encourage you to run through each example. In this tutorial, you saw how to implement single and multiple inheritance in Python. You also saw how to pass parameters from a child class to a parent class constructor and how to inherit from an abstract class. For more tutorials like this, subscribe using the form below:


Get Our Python Developer Kit for Free

I put together a Python Developer Kit with over 100 pre-built Python scripts covering data structures, Pandas, NumPy, Seaborn, machine learning, file processing, web scraping and a whole lot more - and I want you to have it for free. Enter your email address below and I'll send a copy your way.

Yes, I'll take a free Python Developer Kit