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 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
Let’s now create some dummy child classes for the
To inherit the 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,
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
Let’s first create an object of the parent
a = Animal()
a.set_name("Lion")
a.set_age(10)
a.print_name()
Output:
Lion
Next we’ll create an object of 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
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 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
i = Insect()
i.set_name("Butterfly")
i.print_name()
i.print_flying()
Output:
Butterfly
The Butterfly is flying
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
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
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
m = Mammal("monkey", "15", 5)
m.print_name()
print(m.age)
m.print_running
print(m.kids)
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
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 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
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
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 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 methodA
and methodB
respectively. We create another class
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 methodA()
and the parent class methodB()
using the child class
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:
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.