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

Types of Inheritance in Python | Python Inheritance [With Examples]

Updated on 05 July, 2024

32.47K+ views
15 min read

Introduction

The struggle for a clean code is a battle joined by all the programmers. And that battle can be conquered with a proper armour of object-oriented programming concepts. And proper utilization of OOP concepts helps us to improve code reusability, readability, optimal time and space complexity.

Coding in Python is super fun. It has a whopping number of library support, object-oriented, GUI programmability makes it a hot cake among all the programming languages.

By mastering OOP principles like encapsulation, inheritance, polymorphism, and abstraction, Python programmers can build robust and adaptable systems. This methodical approach organizes code and sets a foundation for future growth and adaptability in the fast-changing world of software development. 

Inheritance is one of the most utilized object-oriented features and implementing it in python is an enthusiastic task. So, let’s start now!

It is a crucial part of how objects work together in Python. This blog aims to explore class and inheritance in Python with clear examples and guidance to help you understand and use this concept better. 

First things first let’s understand the definition of inheritance.

Inheritance: What is Inheritance in Python?

Inheritance is a process of obtaining properties and characteristics(variables and methods) of another class. In this hierarchical order, the class which inherits another class is called subclass or child class, and the other class is the parent class.

It’s like a relationship between class and subclass in Python, where one class (the child or subclass) can inherit traits from another class (the parent or superclass).

Here’s an example of inheritance in Python with a simple analogy:

Think of a family tree. The parent class is like the grandparent, and the child class is the grandchild. The grandchild can inherit certain features from the grandparent, such as eye color or hair type, but can also have its own unique qualities.

Let’s consider a ‘Grandparent’ class that holds certain characteristics shared by the family, such as eye color or hair type. Then, a ‘Parent’ class can inherit from the ‘Grandparent,’ gaining those shared traits. Finally, a ‘Child’ class can inherit from the ‘Parent’ class, having its traits and possibly some unique ones.

class Grandparent:

    def __init__(self, eye_color, hair_type):

        self.eye_color = eye_color

        self.hair_type = hair_type

    def describe(self):

        return f"Eye color: {self.eye_color}, Hair type: {self.hair_type}"

# Parent class inheriting from Grandparent

class Parent(Grandparent):

    def __init__(self, eye_color, hair_type, profession):

        super().__init__(eye_color, hair_type)

        self.profession = profession

    def describe(self):

        return f"{super().describe()}, Profession: {self.profession}"

# Child class inheriting from Parent

class Child(Parent):

    def __init__(self, eye_color, hair_type, profession, hobby):

        super().__init__(eye_color, hair_type, profession)

        self.hobby = hobby

    def describe(self):

        return f"{super().describe()}, Hobby: {self.hobby}"

# Creating instances

grandparent = Grandparent("Brown", "Curly")

parent = Parent("Brown", "Curly", "Engineer")

child = Child("Blue", "Straight", "Student", "Playing Guitar")

# Description

print("Grandparent:", grandparent.describe())

print("Parent:", parent.describe())

print("Child:", child.describe())
  • ‘Grandparent’ holds common traits like eye color and hair type.
  • ‘Parent’ inherits from ‘Grandparent’ and adds a profession.
  • ‘Child’ inherits from ‘Parent’ and includes a hobby.

When we create instances of these classes and call their describe() methods, each instance will describe its attributes based on its class and inherited traits. This demonstrates the flow of inheritance, where each subsequent class builds upon the traits inherited from the preceding class.

Also, Check out all Trending Python Tutorial Concepts in 2024.

Benefits of Using Inheritance in Python

Inheritance in Python offers several advantages that significantly benefit developers in building efficient and maintainable code.

  • Code reuse: Inheritance enables the reuse of established code to create new classes. Developers inherit existing methods and attributes from parent classes. Using pre-existing functionalities and structures minimizes repetition and saves time and effort.
  • Access to parent class features: When a class inherits from another, it gains access to the entirety of the parent class’s methods and attributes. This inheritance enables the use of established functionalities and encourages a systematic coding approach where common features are centralized in a base class and shared across various subclasses.
  • Reliability through tested code: Inherited code often originates from thoroughly tested base classes, providing a sense of trust and validation for the functionalities inherited by subclasses when integrated into new contexts.
  • Time and cost efficiency: Reusing tested and validated code significantly reduces development time and costs. Leveraging existing functionalities diminishes the need to build new features from scratch, streamlining the development process and optimizing resource utilization.
  • Consistent interfaces: Inheritance fosters the maintenance of consistent interfaces across related classes. Standardizing how methods and attributes are accessed and used enhances code readability and comprehensibility, facilitating better understanding and management of the codebase.
  • Reducing redundancy: Centralizing shared functionalities in a base class through inheritance minimizes redundant code segments. This consolidation reduces the need for duplicating code and helps avoid inconsistencies or errors within the codebase while enhancing its maintainability.
  • Support for extensions and customization: Inheritance permits the extension and customization of existing functionalities. New classes inherit from base classes and can modify or supplement specific methods or attributes, allowing developers to tailor functionalities to meet specific requirements while retaining the core features provided by the base class.
  • Simplified class libraries development: With inheritance, developers can create reusable class libraries effortlessly. Establishing hierarchical relationships among classes with shared functionalities promotes modular code development. These libraries can be easily reused across different projects, encouraging consistent and efficient development practices.

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.

What is Class and Subclass in Python?

In Python, a class is a blueprint or a template for creating objects. It defines properties (attributes) and behaviors (methods) that the objects belonging to that class will have. In inheritance, a class serves as the base or parent from which other classes, called subclasses or derived classes, can inherit attributes and methods.

A subclass, on the other hand, is a specialized class that inherits from a parent class. It incorporates all the attributes and methods of its parent class while having the ability to define its own additional attributes or methods.

Inheritance in Python allows a subclass to access and use its parent class’s properties and behaviors (methods and attributes). This process promotes code reusability and also a hierarchy in which common functionalities can be defined in the parent class and inherited by multiple subclasses.

What Are The Types of Inheritance in Python?

Inheritance is categorized based on the hierarchy followed and the number of parent classes and subclasses involved.

Python supports five types of inheritance: single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance, and hybrid inheritance. Single inheritance allows a class to inherit from one parent class, enabling straightforward extensions. Multiple inheritance enables a class to inherit from multiple parent classes, combining functionalities but with added complexity. Multilevel inheritance involves a class inheriting from another class, which in turn inherits from a third class, creating a chain. Hierarchical inheritance occurs when multiple classes inherit from a single parent class, promoting shared functionality across different classes. Hybrid inheritance is a mix of two or more types of inheritance, providing flexibility and reusability by combining the features of different inheritance models.

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance
  4. Hierarchical Inheritance
  5. Hybrid Inheritance

Must read: Free excel courses!

Learning about the different types of inheritance in Python opens up multiple ways to organize how classes relate to each other. However, using them wisely is key to maintaining the readability of codes. 

Each type of inheritance has its own strengths, so picking the right one depends on what the program needs and how it’s set up. Let’s learn more about the different types of inheritance in Python with examples in this comprehensive guide.

Single Inheritance

What is single inheritance in python? This type of inheritance enables a subclass or derived class to inherit properties and characteristics of the parent class, this avoids duplication of code and improves code reusability.

It is fundamental and straightforward, enabling the subclass to acquire all the attributes and methods of its parent class.

By implementing single inheritance, classes can organize their relationships in a linear structure, where a class inherits from a single parent. This helps avoid redundancy in code by allowing the subclass to access and utilize the functionalities defined in the parent class.

Single inheritance promotes code reusability and supports the principle of DRY (Don’t Repeat Yourself), as it eliminates the need to duplicate code. It simplifies the class hierarchy, making it easier to understand and maintain. However, while single inheritance provides a clear and manageable structure, it may not cover scenarios where a class needs traits from multiple sources, where multiple inheritance might be more suitable.

Here is an example illustrating this Python class inheritance:

Single inheritance in Python example

#parent class
class Above:
    i = 5
    def fun1(self):
        print(“Hey there, you are in the parent class”)

#subclass
class Below(Above):
    i=10
    def fun2(self):
        print(“Hey there, you are in the sub class”)

temp1=Below()
temp2=Above()
temp1.fun1()
temp1.fun2()
temp2.fun1()
print(temp1.i)
print(temp2.i)
#temp2.fun2()

Alright, let’s walk through the above code.

In the above code “Above” is the parent class and “Below” is the child class that inherits the parent class. Implementing inheritance in python is a simple task, we just need to mention the parent class name in the parentheses of the child class. We are creating objects of both parent class and child class, and here comes an interesting point about the inheritance. A child class can access the methods and variables of the parent class, whereas the vice versa is not true.

So in the above code temp1 object can access both fun1 and fun2 methods whereas the temp2 object can access only the fun1 method. Similarly, the same rule applies to variables in the code. And accessing a child class method or variable from a parent class object will throw an error. If the last line in the code is uncommented then it raises an error.

Our learners also read – python free courses!

Multiple Inheritance

What is multiple inheritance in python? This inheritance enables a child class to inherit from more than one parent class. This type of inheritance is not supported by java classes, but python does support this kind of inheritance. It has a massive advantage if we have a requirement of gathering multiple characteristics from different classes.

Multiple inheritance in Python lets a class use traits from more than one parent class. This helps create flexible classes that combine different behaviors and features. However, handling multiple inheritances requires careful thought to keep the code clear and avoid complications from interactions between the different parent classes.

To help define this inheritance in Python, here is an illustrated example: 

Multiple inheritance in python example

#parent class 1
class A:
    demo1=0
    def fun1(self):
        print(self.demo1)

#parent class 2
class B:
    demo2=0
    def fun2(self):
        print(self.demo2)

#child class
class C(A, B):
    def fun3(self):
        print(“Hey there, you are in the child class”)

# Main code
c = C()
c.demo1 = 10
c.demo2 = 5
c.fun3()
print(“first number is : “,c.demo1)
print(“second number is : “,c.demo2)

In the above code, we’ve created two parent classes “A”, “B”. Following the syntax of the inheritance in python, we’ve created a child class, which inherits both classes “A” and “B”. As discussed earlier that a child class can access the methods and variables of the parent class, The child class “C” can access the methods of its parent class.

 

upGrad’s Exclusive Data Science Webinar for you –

ODE Thought Leadership Presentation

Multilevel Inheritance

What is multilevel inheritance? In multilevel inheritance, the transfer of the properties of characteristics is done to more than one class hierarchically. To get a better visualization we can consider it as an ancestor to grandchildren relation or a root to leaf in a tree with more than one level.

It is a hierarchical inheritance in Python where a subclass is created from another subclass, which itself is derived from a parent class. This creates a chain or hierarchy of classes, where each subclass inherits traits from its immediate parent and from the classes further up in the hierarchy. This way, the properties trickle down the chain, allowing for the inheritance of attributes and methods from multiple levels.

Understanding multilevel inheritance helps build a clear and structured class hierarchy, facilitating code organization and reuse. However, while designing classes using multilevel inheritance, it’s important to maintain simplicity and prevent unnecessary complexity arising from extensive inheritance chains.

To help explain this inheritance in Python, here is an example:

Multilevel inheritance in Python example

#parent class 1
class vehicle:
    def functioning(self):
        print(“vehicles are used for transportation”)

#child class 1
class car(vehicle):
    def wheels(self):
        print(“a car has 4 wheels”)
       
#child class 2
class electric_car(car):
    def speciality(self):
        print(“electric car runs on electricity”)

electric=electric_car()
electric.speciality()
electric.wheels()
electric.functioning()

Having a dry run over the above code, we’ve created a class “vehicle”, then we’ve created a class car that inherits the class vehicle. Now the “vehicle” is a parent class and the “car” is a child class. Later we’ve created an “electric_car” class, now the car class is a parent class and the electric_car class is a child class, and the relationship between vehicle class and electric_car class is the multilevel inheritance.

Must read: Data structures and algorithm free!

Here electric_car class can access the methods, variables of both vehicle and car class, whereas car class can access only the methods, variables of vehicle class. And as discussed parent class vehicle cannot access any method of the child class.

Hierarchical Inheritance

What is hierarchical inheritance? This inheritance allows a class to host as a parent class for more than one child class or subclass. This provides a benefit of sharing the functioning of methods with multiple child classes, hence avoiding code duplication.

In hierarchical inheritance, a parent class allows multiple child classes to inherit its attributes and methods. This setup avoids repeating code by sharing common functionalities among subclasses. The parent class’s methods and attributes are accessible to all its child classes, promoting code reuse and improving organizational efficiency.

Developers use this Python class inheritance to create a well-organized class system. This approach minimizes redundancy and streamlines development with shared functionalities across related classes. 

However, it’s important to maintain clear and straightforward code, avoiding unnecessary complexity when arranging classes in this hierarchical structure. This balance ensures a more manageable and understandable codebase, supporting efficient development practices.

#parent class
class Parent:
    def fun1(self):
        print(“Hey there, you are in the parent class”)
 
#child class 1
class child1(Parent):
    def fun2(self):
        print(“Hey there, you are in the child class 1”)

#child class 2 
class child2(Parent):
    def fun3(self):
        print(“Hey there, you are in the child class 2”)
 
#child class 3
class child3(Parent):
    def fun4(self):
        print(“Hey there, you are in the child class 3”)
 
# main program
child_obj1 = child3()
child_obj2 = child2()
child_obj3 = child1()
child_obj1.fun1()
child_obj1.fun4()
child_obj2.fun1()
child_obj2.fun3()
child_obj3.fun1()
child_obj3.fun2()

In the above code, we have a single parent class and multiple child classes inheriting the same parent class. Now all the child classes can access the methods and variables of the parent class. We’ve created a “Parent” class and 3 child classes “child1”, “child2”, “child3”, which inherits the same parent class “Parent”.

Checkout: Python Open Source Project Ideas

Hybrid Inheritance

What is hybrid inheritance? An inheritance is said hybrid inheritance if more than one type of inheritance is implemented in the same code. This feature enables the user to utilize the feature of inheritance at its best. This satisfies the requirement of implementing a code that needs multiple inheritances in implementation.

This feature enables developers to combine various inheritance types, creating complex class relationships. By using multiple forms of inheritance, programmers can design classes that meet specific requirements demanding multiple inheritances.

Hybrid inheritance offers a flexible approach to building intricate class structures using diverse inheritance types. However, using this feature carefully is crucial to keep the code clear and prevent complications that may arise from interactions between different inheritance types.

Here, we have illustrated the Hybrid types of inheritance in Python with an example:

Hierarchical inheritance in Python example

class A:
def fun1(self):
print(“Hey there, you are in class A”)class B(A):
def fun2(self):
print(“Hey there, you are in class B”)class C(A):
def fun3(self):
print(“Hey there, you are in class C”)class D(C,A): #line 13
def fun4(self):
print(“Hey there, you are in the class D”)#main program
ref = D()
ref.fun4()
ref.fun3()
ref.fun1()

In the above code, we can see that we’ve implemented more than one type of inheritance. Classes A, B, C implements hierarchical inheritance, and classes A, C, D implements multilevel inheritance. Noe those individual inheritances have their individual properties of accessing methods and variables of the parent class. Also, there’s a point to be noted.

When we are implementing multilevel inheritance we follow syntax like “child_class(parent_class1, parent_class2)”. But this syntax will throw an error if “parent_class1” is hierarchically above the “parent_class2”. If we want to implement this syntax, then the “parent_class1” must be in a hierarchically lower level than “parent_class2”. For example in the above code, if line 13 has a syntax class D(A, C) then the code wouldn’t work since class C is hierarchically lower than class A.

Learn data science courses from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read: Python Project Ideas & Topics

Conclusion

We’ve gone through the uses and needs of inheritance and understood the definition of inheritance. Also, we’ve gone through the types of inheritance and walked through the implementation codes and explanations of each type of inheritance. Understood the rules of variables and method accessing in different types of inheritances.

Now that you are aware of different types of inheritances in python, try implementing them and try utilizing them in your code. Try optimizing your code with the proper utilization of inheritance.

If you are curious to learn about data science, check out IIIT-B & upGrad’s PG Diploma 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. What is the difference between multiple inheritance and multilevel inheritance?

Many beginner programmers often get confused between multiple inheritance and multilevel inheritance. The following illustrates some of the significant differences between these two types of inheritance.
Multiple Inheritance -
1. When a child class inherits its properties and characteristics from more than one base class, such type of inheritance is known as Multiple Inheritance.
2. It is not used widely since the Multiple Inheritance can be quite complex to understand.
3. It has only two class levels: base class and derived class.
Multilevel Inheritance
1. The inheritance in which a child class inherits the properties from its base class which is further inheriting the properties from another base class, making the former a child class is known as Multilevel Inheritance.
2. This inheritance serves great purposes and hence is used much widely.
3. It has at least three class levels: base class, intermediate class, and derived class.

2. What do you understand about Hybrid Inheritance?

Hybrid Inheritance is a unique type of inheritance. Rather than having a new concept, as its name suggests it is a combination of two or more types of inheritances. For example, a class showing both multiple and multilevel inheritances is an example of hybrid inheritance.

3. What do you know about access modifiers in Python?

In Python, there are 3 types of access modifiers that are mentioned below:
1. Public Access Modifier - The Public members of a class are accessible by any part of the program. In Python, if the access specifier of data members or member functions is not specified then it is public by default.
2. Protected Access Modifier - If a data member or a member function is defined as protected then it is only accessible by the derived classes of that class.
3. Private Access Modifier - The private access modifier is the most secure access specifier. The private members are only accessible within the class in which they are defined.