Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconInheritance in Python | Python Inheritance [With Example]

Inheritance in Python | Python Inheritance [With Example]

Last updated:
27th Feb, 2024
Views
Read Time
10 Mins
share image icon
In this article
Chevron in toc
View All
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. Check out our data science certifications if you are eager to gain expertise in python and other tools.

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() 

Our learners also read: Top Python Courses for Free

Explore our Popular Data Science Courses

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 all trending Python tutorial concepts in 2024

In the realm of Python programming, inheritance emerges as a cornerstone concept, empowering you to leverage the power of code reuse and establish well-organized class hierarchies. By inheriting attributes and methods from existing classes (known as base classes), you can streamline development, promote maintainability, and foster an intuitive object-oriented approach.

Delving into the Syntax:

Example of inheritance in python

The foundation of inheritance in Python lies in its straightforward syntax:

Python

class DerivedClassName(BaseClassName):

# class body

Here, DerivedClassName inherits from BaseClassName, allowing it to access and modify inherited members, thereby exemplifying class and inheritance in Python.

Here, DerivedClassName represents the class inheriting attributes and methods, while BaseClassName signifies the base class providing the inheritance blueprint. This simple syntax establishes a clear relationship, enabling the derived class to access and potentially modify inherited members.

Crafting a Parent Class:

The journey begins with establishing a parent class, serving as the foundation for future inheritance. Imagine creating a class named Animal to represent general animal characteristics:

Python

class Animal:

def __init__(self, species):

self.species = species

def sound(self):

print(“Animal makes a sound”)

This parent class sets the stage for inheritance, introducing a foundation upon which class Python inheritance can be demonstrated.

This Animal class defines an __init__() method to initialize the species attribute and a sound() method to represent a generic animal sound.

Introducing the Child Class:

Now, let’s create a Dog class that inherits from the Animal class:

Python

class Dog(Animal):

def __init__(self, species, breed):

super().__init__(species)

self.breed = breed

def sound(self):

print(“Dog barks”)

The Dog class inherits from Animal by specifying its parent in the definition. It also defines its own __init__() method to introduce the breed attribute and overrides the sound() method to reflect a dog’s characteristic bark.

Eager to put your Python skills to the test or build something amazing? Dive into our collection of Python project ideas to inspire your next coding adventure.

Witnessing Inheritance in Action:

Here’s a practical example showcasing how inheritance works:

Python

class Animal:

def __init__(self, species):

self.species = species

def sound(self):

print(“Animal makes a sound”)

class Dog(Animal):

def __init__(self, species, breed):

super().__init__(species)

self.breed = breed

def sound(self):

print(“Dog barks”)

# Creating instances of classes

animal = Animal(“Canine”)

dog = Dog(“Canine”, “Labrador”)

# Calling methods

animal.sound()  # Output: Animal makes a sound

dog.sound() # Output: Dog barks

As you can see, the Dog class inherits the sound() method from Animal, but also provides its own specific implementation. This demonstrates the advantages of inheritance in Python.

By integrating this inheritance example in Python into our discussion, we can see the versatility and power of inheritance in creating an organized and efficient class hierarchy.

Additional Considerations:

While inheritance offers distinct advantages, it’s crucial to use it judiciously. Consider these tips:

Favor composition over inheritance: When possible, favor composing objects from smaller, reusable components instead of extensive inheritance hierarchies.

Understand multiple inheritance complexities: While Python supports multiple inheritance, it can introduce ambiguity and complexities, so use it cautiously.

Maintain clear class hierarchies to ensure code readability and maintainability, touching on concepts like hybrid inheritance in Python and hierarchical inheritance in Python.

By understanding what is inheritance in Python with examples and adhering to best practices, developers can leverage inheritance effectively to create robust and scalable applications.

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)

upGrad’s Exclusive Data Science Webinar for you –

How to Build Digital & Data Mindset

 

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

Top Data Science Skills to Learn

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.

Master of Science in Machine Learning & AI: IIIT Bangalore, 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. 

If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1Why is inheritance significant in Python?

Inheritance refers to the process of passing on the properties of a parent class to a child class. It is an object-oriented programming(OOP) concept and is significant in Python. It is because inheritance provides code reusability, which means that instead of writing the same code over and again, we can inherit the attributes we require in a child class. It is also easy to understand and implement since it depicts a real-world relationship between the parent and child classes. It has a transitive nature. Because all child classes inherit properties from their parents, any subclasses will likewise use the parent class's functionalities.

2Is inheritance necessary while learning Python?

Yes, learning inheritance is necessary while learning Python. Massive python applications necessitate a rise in the number of python programmers in the current market. This surge has led to an increase in the number of people learning Python. The Python programming language is rich in notions such as inheritance. One of the essential concepts in this Object-oriented programming language is inheritance. As inheritance allows for code reusability, readability, and properties transition, learning it while learning Python is imperative. Inheritance aids in creating accurate and efficient code.

3In Python, which types of inheritance are not supported?

Python allows all forms of inheritance, including multiple inheritances, unlike other object-oriented programming languages. It is possible to construct new classes from pre-existing ones using the inheritance concept. This facilitates the reuse of code. The methods specified in the parent class are also used in the child class. While C++ also enables this sort of inheritance, it lacks Python's advanced and well-designed methodology. Python even offers Hybrid inheritance, which allows us to implement many types of inheritance in a single piece of code. Because code reusability is a strength of inheritance, it is helpful in a wide range of applications when working with Python.

Explore Free Courses

Suggested Blogs

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905071
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions & Answers [For Freshers & Experienced]
20833
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5062
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5149
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10764
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80583
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
138972
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
68962
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon