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

Linear Search vs Binary Search: Difference Between Linear Search & Binary Search
66143
In my journey through data structures, I’ve navigated the nuances of linear search vs binary search in data structure, especially when dealing w
Read More

by Rohit Sharma

23 Jun 2024

Information Retrieval System Explained: Types, Comparison & Components
64450
An Information Retrieval System is a set of algorithms that facilitate the relevance of displayed documents to searched queries. In simple words, it w
Read More

by Rohit Sharma

18 Jun 2024

4 Types of Trees in Data Structures Explained: Properties & Applications
61761
In this article, you will learn about the Types of Trees in Data Structures with examples, Properties & Applications. In my journey with data stru
Read More

by Rohit Sharma

31 May 2024

Searching in Data Structure: Different Search Methods Explained
40594
The communication network is expanding, and so the people are using the internet! Businesses are going digital for efficient management. The data gene
Read More

by Rohit Sharma

29 May 2024

What is Linear Data Structure? List of Data Structures Explained
54956
Data structures are the data structured in a way for efficient use by the users. As the computer program relies hugely on the data and also requires a
Read More

by Rohit Sharma

28 May 2024

4 Types of Data: Nominal, Ordinal, Discrete, Continuous
318837
Summary: In this Article, you will learn about what are the 4 Types of Data in Statistics. Qualitative Data Type Nominal Ordinal Quantitative Data
Read More

by Rohit Sharma

28 May 2024

Python Developer Salary in India in 2024 [For Freshers & Experienced]
909244
Wondering what is the range of Python developer salary in India? Before going deep into that, do you know why Python is so popular now? Python has be
Read More

by Sriram

21 May 2024

Binary Tree in Data Structure: Properties, Types, Representation & Benefits
89686
Data structures serve as the backbone of efficient data organization and management within computer systems. They play a pivotal role in computer algo
Read More

by Rohit Sharma

21 May 2024

Data Analyst Salary in India in 2024 [For Freshers & Experienced]
23871
Summary: In this Article, you will learn about Data Analyst Salary in India in 2024. Data Science Job roles Average Salary per Annum Data Scient
Read More

by Shaheen Dubash

20 May 2024

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