Programs

Inheritance in Python | Python Inheritance [With Example]

Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-oriented programming language has seen a massive jump in popularity. 

If you plan for a career as a Python developer, you are bound to have a higher payout. As the average salary for a Python developer is around $119,082 per year. But, before you go ahead with the Python learning program, here is something that you should know first- Inheritance in Python. 

Let’s first begin with what exactly is inheritance in Python?

What is an inheritance in Python?

Just like a parent-child relationship, inheritance works on derived classes relative to the base class. Every “Derived” class inherits from a “Base” class. The inheritance is represented in UML or Unified Modeling Language. It is a standard modeling language that includes an integrated set of diagrams to help developers specify, structure, and document software systems elements. 

Inheritance relationship defines the classes that inherit from other classes as derived, subclass, or sub-type classes. Base class remains to be the source from which a subclass inherits. For example, you have a Base class of “Animal,” and a “Lion” is a Derived class. The inheritance will be Lion is an Animal.  

So, the question is, what does the “Lion” class inherit from “Animal”? 

A “Lion” class inherits

  • Interface
  • Execution 

Note: You can replace the Derived Class objects with Base Class objects in an application known as the Liskov substitution principle. It indicates that if a computer program has object P as the subtype of Q, you can easily replace P with Q without altering the properties. 

Also Checkout: Python Developer Salary in India

Advantages of Inheritance in Python

  • Inheritance in Python helps developers to reuse the objects.
  • Each time a class inherits the base class, it gets access to the parent object’s functionality. 
  • Reusability due to inheritance is also reliable as the base class is already tested. 
  • Low development time and cost
  • Standardization of the interface across classes becomes easy.
  • Reduces redundancy of code and help improve extensibility
  • The creation of class libraries becomes easy.

Types of Inheritance in Python

Single Inheritance

We have already seen what single inheritance is- the inheritance of the “Derived” class from the “Base” class. Let’s understand it through an example, 

class Country:

     def ShowCountry(self):

         print(“This is Spain”);

class State(Country):

     def ShowState(self):

         print(“This is State”);

st =State();

st.ShowCountry();

st.ShowState();

Multi-Level inheritance

Python is made of several objects, and with the multi-level inheritance, there are endless possibilities of reusing the class functionalities.  Multi-level inheritance gets documented each time a derived class inherits another derived class. There is no limit to the number of derived classes that can inherit the functionalities, and that is why multilevel inheritance helps to improve the reusability in Python. 

Here is an example of multilevel inheritance

class Animal:  

    def speak(self):  

        print(“Animal Speaking”)  

#The child class Dog inherits the base class Animal  

class Dog(Animal):  

    def bark(self):  

        print(“dog barking”)  

#The child class Dogchild inherits another child class Dog  

class DogChild(Dog):  

    def eat(self):  

        print(“Eating bread…”)  

d = DogChild()  

d.bark()  

d.speak()  

d.eat() 

Multiple Inheritance

Python enables developers to inherit multiple functionalities and properties from different base classes into a single derived class. It is mostly a great feature as it can allow you to inherit multiple dependencies without extensive tools or coding. 

Let’s look at an example for multiple inheritances.

class Calculation1:  

    def Summation(self,a,b):  

        return a+b;  

class Calculation2:  

    def Multiplication(self,a,b):  

        return a*b;  

class Derived(Calculation1,Calculation2):  

    def Divide(self,a,b):  

        return a/b;  

d = Derived()  

print(d.Summation(10,20))  

print(d.Multiplication(10,20))  

print(d.Divide(10,20))

Check out: How To Convert Speech to Text with Python

How to identify a Derived Class?

Python comes with a built-in issubclass() function that helps developers check whether a class is a derived one or a base class. Once you run this function, it returns with a result “True” for subclass or a Derived class, while False for Base class.

A developer can check the class through this example.

class myAge:

  age = 36

class myObj(myAge):

  name = “John”

  age = myAge

x = issubclass(myObj, myAge)

How to create a class hierarchy in Python?

Inheritance in Python helps create hierarchies of classes. All the relative classes will share a common interface to communicate with each other. A Base class defines the interface. Derived classes can provide specific specialization of the interface. Here, we are exploring an HR model to demonstrate the class hierarchy. 

The HR system will process payroll for different company workers; each worker is identified through an ID and has different payroll positions to be calculated. 

Let’s first create a payroll class as the “Base” object.

# In hr.py

class PayrollSystem:

    def calculate_payroll(self, workers):

        print(‘Calculating Payroll’)

        print(‘===================’)

        for worker in workers:

            print(f’Payroll for: {worker.id} – {worker.name}’)

            print(f’- Check amount: {worker.calculate_payroll()}’)

            print(”)

The PayrollSystem executes a .calculate_payroll()method that collects the worker’s information, prints their id, name, and checks the payroll amount. Now, you run a base class worker that tackles the standard interface for every worker type:

# In hr.py

class Worker:

    def __init__(self, id, name):

        self.id = id

        self.name = name

Creating a Worker base class for all the worker types in the company makes the hierarchy easy for the HR system. Every worker is assigned a name and id. The HR system requires the worker to provide data regarding their weekly salary through the  .calculate_payroll() interface. The execution of this interface may differ according to the type of worker.

Must Read: Python Interview Questions

Conclusion

Here, we learned to create different Python classes, establish relationships between them, and even set class hierarchy. But, inheritance in Python is not limited to the functionalities mentioned here.

Advance Certification in Machine Learning and AI: IIT madras, one of the best educational institutions of India, has partnered with upGrad to make an advanced course on Machine Learning for individuals to have complete knowledge of Machine Learning with this course. 

Prepare for a Career of the Future

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN DATA SCIENCE
Learn More

Leave a comment

Your email address will not be published.

Accelerate Your Career with upGrad

Our Popular Data Science Course

×