Python

Python Inheritance with Examples

In this article, we will explain Inheritance in Python using examples

1. Introduction

Python is an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

Python classes provide all the standard features of Object-Oriented Programming: the class inheritance mechanism allows multiple base classes, a derived class can override any methods of its base class or classes, and a method can call the method of a base class with the same name. Base class must be defined in a scope containing the derived class definition.

In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object (prototype-based inheritance) or class (class-based inheritance), retaining similar implementation. Inheritance allows us to define a class that inherits all the methods and properties from another class. The parent class is the class being inherited from, also called the base class.

2. Python Inheritance Example

In this section, we will try to explain how inheritance works in Python. Let us create a Base class called Shape:

class Shape:
    def __init__(self, numberOfEdges):
        self.numberOfEdges = numberOfEdges

    def printNumberOfEdges(self):
    print("Base class -> Number of Edges:", self.numberOfEdges)

The class has two methods – __init__ and printNumberOfEdges. __init__ is a reserved method in python classes. It is known as a constructor in object-oriented concepts. This method is called when an object is created from the class and it allows the class to initialize the attributes of a class. The __init__ method takes two parameters: self and numberOfEdges. The self parameter refers to the instance of the object (like this in C++ and Java). The other method prints the number of edges in the shape.

Now let us define a child class that inherits the properties and methods from this base class Shape. To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class

class Triangle(Shape):
    pass

Use the pass keyword when you do not want to add any other properties or methods to the class. Now the child class Triangle has the same properties and methods as the base class Shape. Now let’s use the Triangle class to create an object, and then execute the printNumberOfEdges method:

triangle = Triangle(3)
triangle.printNumberOfEdges()

Below is the full source code:

class Shape:
    def __init__(self, numberOfEdges):
        self.numberOfEdges = numberOfEdges

    def printNumberOfEdges(self):
        print("Base class -> Number of Edges:", self.numberOfEdges)

class Triangle(Shape):
    pass

triangle = Triangle(3)
triangle.printNumberOfEdges()

When you run the above code you will see the output as Base class -> Number of Edges: 3

So far we have created a child class that inherits the properties and methods from its parent. Now let us add the printNumberOfEdges method in the child class Triangle:

class Shape:
    def __init__(self, numberOfEdges):
        self.numberOfEdges = numberOfEdges

    def printNumberOfEdges(self):
        print("Base class -> Number of Edges:", self.numberOfEdges)

class Triangle(Shape):
    def printNumberOfEdges(self):
        print(" Triangle -> Number of Edges:", self.numberOfEdges)

triangle = Triangle(3)
triangle.printNumberOfEdges()

When you run the above code you will see the output as Triangle -> Number of Edges: 3 When you add the printNumberOfEdges() function, the child class will no longer inherit the parent’s printNumberOfEdges() function. You can still call the base class method inside the overridden method if you want using the base class reference:

class Triangle(Shape):
    def printNumberOfEdges(self):
        print("Triangle -> Number of Edges:", self.numberOfEdges)
        Shape.printNumberOfEdges(self) # Call the base class method

The other and better way of calling the base class methods is by using the super() function. By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

We can also add methods in the child class. Let’s add a method in the Triangle class which prints the formula of finding the area of the shape:

def printAreaFormula(self):
    print("Area of triangle", "(base * height)/2")

We can now call this new method of the child class:

triangle = Triangle(3)
triangle.printAreaFormula()

Python has two built-in functions that work with inheritance:

  • Use isinstance() to check an instance’s type: isinstance(obj, Triangle) will be True only if obj.__class__ is
  • Triangle or some class derived from Triangle.
  • Use issubclass() to check class inheritance: issubclass(Triangle, Shape) is True since Triangle is a subclass of Shape.

All the three statements below will output True:

print(isinstance(triangle, Triangle))
print(isinstance(triangle, Shape))
print(issubclass(Triangle, Shape))

3. Summary

When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.

In this article, we looked at what Inheritance means in Object-Oriented Programming and how Python uses it. We discussed the ways of making a class inherit the properties and behavior of another class. In the end, we discussed some useful methods which we can use for checking if a class is inheriting the behavior of another class or not.

4. Download the Source Code

This was an example of Python Inheritance.

Download
You can download the full source code of this example here: Python Inheritance with Examples

Mohammad Meraj Zia

Senior Java Developer
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button