Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Inheritance in Python | Python Inheritance [With Example]

Updated on 19 March, 2024

18.91K+ views
10 min read

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

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

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.

Frequently Asked Questions (FAQs)

1. Why 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.

2. Is 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.

3. In 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.