Inheritance in Python

Inheritance-in-Python-Feature-Image.jpg

Inheritance is one of the four pillars of object-oriented programming in Python, the other three are Abstraction, Encapsulation, and Polymorphism. It allows you to create new classes that reuse, extend, or modify the behaviour of existing ones. This reduces the code’s redundancy and makes the code more scalable and easier to maintain. In this blog, we will understand the concept of inheritance in Python, its classifications, implementation, and how to leverage it to write clean, understandable code.

Table of Contents:

Understanding Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) organises code using classes and objects, making it clean, reusable, and easier to understand. For example, an EdTech company has multiple departments like HR, Sales, Technical Writing, and Design, offering courses in Data Science, AI, Cyber Security, and more.

Without OOP, representing each department and course separately would make the code repetitive, lengthy, and hard to maintain. OOP allows us to model real-world entities like Employee or Course as structured, reusable blocks. This approach reduces code duplication, improves organisation, and creates modular, maintainable programs that accurately reflect real-world systems.

Object-oriented programming in Python is built on four core principles, also known as the four pillars of OOP. These are:

object-oriented programming (OOP) in Python
To Learn More about Inheritance and Advance Your Career with Python - Sign up now!
Expert-led. Project-based. Certificate included.
quiz-icon

Let us now discuss Inheritance in Python from scratch with relevant examples:

Inheritance in Python OOP

Inheritance in Python is a mechanism that allows one class (called the child class or subclass) to access the properties and methods of another class (called the parent class or superclass). It implements a class based on an existing class, making our code more organised, reusable, and easier to maintain.

Example:

Python

Output:

Inheritance in Python output

Explanation: In this example, we have a parent class named Employee and a child class named HR that inherits from the parent class.

Syntax of Inheritance in Python

To implement Inheritance in Python, you need to have two classes implemented. One base class that would serve as the parent class and one child class. The child class would inherit the methods or properties from the base or parent class. Let us now learn how to create a parent class and a child class.

How to Create a Parent Class in Python Inheritance

A parent class (or base class) in Python defines the general attributes and methods that can be reused by one or more child classes. It is declared like any other class in Python. This also means that any existing class can act as a parent class. The syntax of declaring a parent class is

Syntax:

class parent_class_name():
            pass

Example:

Let us implement an Employee class for Intellipaat in Python with a name and an emp_id attribute and a display_info() method.

Python
create a parent class

How to Create a Child Class in Python Inheritance

A child class inherits from the parent class. This means that the child class automatically gains all the properties and methods of the parent, but can also define its own. The syntax of the child class is:

Syntax:

class child_class_name(parent_class):
            pass

Example:

Let us implement a child class, Technical Content Writer, that is a type of Employee and would benefit from inheriting the features of the Employee Parent class.

Python

The TechnicalWriter class inherits the __init__ and display_info() method, name, and emp_id  attribute. In addition to this, the class implemented its method by the name role().

How to Create a Child Class in Python

You know that the child class inherited the attribute as well as the method of the parent class. But how would you call these parent class methods in your child class? Python offers a super() function to carry out that task.

Super() Function in Python Inheritance

The super() function in Python allows a child class to access methods and properties of its parent class without explicitly naming it. It is particularly useful in inheritance, enabling code reuse and avoiding duplication. Python follows the Method Resolution Order (MRO) to determine which parent method to call, ensuring methods are executed in the correct order. Using super() makes code flexible, maintainable, and error-free, especially in complex or multiple inheritance scenarios. It also allows child classes to extend or partially reuse parent methods, making object-oriented programming more efficient and organised.

Types of Inheritance in Python

Python supports various methods of Inheritance. These differ in how many parent classes and child classes are involved, and how they are related to each other. Let us learn about these methods with the help of the Intellipaat system example.

Here is a quick comparison table to better understand the different forms of inheritance in Python. This helps visualise the relationships between base and derived classes in each type of inheritance.

Inheritance Type Description Example Classes
Single One parent → One child Employee → HR
Multiple Two parents → One child ContentCreator, Editor → TechnicalWriter
Multilevel Grandparent → Parent → Child Employee → TechnicalStaff → TechnicalWriter
Hierarchical One parent → Many children Employee → HR, TechnicalWriter
Hybrid Combination of multiple types Real-world scenarios mixing single/multiple forms

1. Single Inheritance

In this type of inheritance, the child inherits from a single class. This is the most basic form of inheritance.

Syntax:

child_class(parent_class):
            pass

Example:

Python

Output:

Single Inheritance output

Explanation: In this example, the TechnicalWriter inherits from a single parent class that is Employee. The TechnicalWriter class inherits the name attribute from the Employee class and then uses it in the output.

Single Inheritance

Since the name attribute was inherited from Employee, this class became the parent class. The TechnicalWriter inherited the attribute, so it became the child class. This is Single Inheritance.

2. Multiple Inheritance

In multiple Inheritance, the child class inherits from more than one parent class. This method is useful when the child class must inherit different Python functions from varied classes. For example, A Technical Content Writer is a mix of Content Creator and Editor who specialises in both jobs. In Python, it means that it will inherit from both classes.

Syntax:

child_class(parent_class1, parent_class2):
            pass

Example:

Python

Output:

multiple inheritance output

Explanation: Here, we made an object of the TechnicalWriter class. Since it inherited from both Content Creator and Editor classes, the object could access the methods of these classes as well, namely create_video() and edit_document().

Multiple Inheritance

The TechnicalWriter class inherits from both Content Creator and Editor. It can use methods from both classes, showcasing multiple inheritance. This is Multiple Inheritance.

3. Multilevel Inheritance

You should not confuse this with multiple inheritance. In multilevel inheritance, a class is derived from another class. In other words, it forms a chain of inheritance. The child class inherits from the parent class, which inherits from the grandparent class.

Syntax:

class ParentClass(GrandparentClass):
    pass
class ChildClass(ParentClass):
    pass

Example:

Python

Output:

multilevel inheritance output

Explanation: Here, TechnicalWriter inherits from TechnicalStaff and gets access to the write_documentation() method. Now the TechnicalWriter also inherited from the TechnicalStaff. Because of this, the object of TechnicalWriter could also access the show_role() method even without inheriting from the Employee class.

Multilevel Inheritance

This is the visual representation of the order of inheritance in the above example of multi-level inheritance.

Get 100% Hike!

Master Most in Demand Skills Now!

4. Hierarchical Inheritance

In this type of inheritance, multiple child classes inherit from the same parent class. For example, both the HR class and the TechnicalWriter inherit from the Employee class.

Syntax:

parent_class:
            pass
child_class1(parent_class):
            pass
child_class2(parent_class):
            pass

Example:

Python

Output:

hierarchical inheritance output

Explanation: Here, hierarchical inheritance is shown where both TechnicalWriter and HR classes inherit from the same parent class, Employee.

Hierarchical Inheritance

This is the visual representation of how hierarchical inheritance works in OOP. The Employee class is the parent class, and both HR and Technical Writer are child classes that inherit common properties and behaviours (attributes and methods) from the parent class.

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more types of inheritance. Since the method is inheriting from more than one class and in more than one way, it is prone to errors due to increasing complexity. Python resolves method inheritance conflicts in hybrid inheritance using Method Resolution Order (MRO).

You can inspect the MRO of any class using the className.__mro__ attribute or className.mro() method. This determines the order in which methods are inherited and executed with the help of the super() function. MRO is handled automatically by Python, so developers don’t need to manually specify the resolution path.

Example:

Python

Output:

Hybrid inheritance output

Explanation: Here, the DataScienceCourse class inherits from both Course and Certification, showing multiple inheritance. The DataScienceCourse also inherits using multilevel inheritance as it can access the basic_info() method from the Course class.

Hybrid Inheritance
  • ProgrammingCourse inherits from Course. This is multilevel inheritance.
  • DataScienceCourse inherits from both ProgrammingCourse and Certification. This is multiple inheritance.
  • Overall, this is an example of hybrid Inheritance.

While inheritance allows one class to inherit attributes and behaviours from another in so many ways, there is another concept called composition that is generally confused with inheritance.

Difference Between Inheritance and Composition in Python

Feature Inheritance Composition
Definition One class is a type of another class One class uses another class inside it
Relationship Type “Is-a” relationship “Has-a” relationship
Code Reuse Child class reuses parent class code Class uses another class’s object to do work
Flexibility Less flexible. Changing base class affects all subclasses. More flexible. Changes in one class don’t affect others much.
When to Use Use when classes are closely related Use when combining features from different classes
Example A Dog is an Animal A Car has an Engine

Let us look at an example to understand the difference between the concepts more clearly.

Inheritance

Example:

Python

Output:

Diff between Inheritance and composition - Inheritance

Explanation: Here, inheritance lets TechnicalWriter use the show_info() method from the Employee class along with its own method.

Composition

Example:

Python

Output:

Diff between Inheritance and composition - Composition

Explanation: Here, composition is used where the Course class includes a Certificate object to show course and certificate details together.

Sometimes, when designing large systems, you want to create a blueprint for other classes without allowing it to be used directly. This is where Abstract Base Classes (ABCs) in Python make developing and coding easy for you.

Method Overriding in Python: Redefining Inherited Behaviour

Method overriding allows the child class to customise a method already defined in the parent class. The child class “overrides” the method, meaning it redefines how the method behaves in the context of the child class. This is essential as it modifies the inherited methods to suit the needs of the child class. It does so without requiring any changes to the code implementation of the parent class.

In Python, method overriding is done by defining a method in the child class with the same name and signature (parameters, arguments, and behaviours) as the method in the parent class.

Example:

Let us take a method from the Employee class and override it in the TechnicalWriter class. The Employee class has a display_info() method that prints the employee’s name and ID. Suppose the TechnicalWriter class wants to include an additional piece of information, its speciality. Instead of writing a completely new method, we can override the existing one from the parent class.

Python

Output:

Method Overriding in Python

Explanation: As you can see in the example, we didn’t have to rewrite the whole code, instead, we overrode the existing display_info() function.

Abstract Base Classes(ABCs) in Python

An Abstract Base Class, one of the advanced Python Inheritance techniques, acts exactly like a blueprint. It will define all the methods that your child class must have, but doesn’t provide actual implementations itself. It is useful when you want to ensure that certain methods exist in all subclasses. Using abstract classes creates a compulsion. You cannot create an instance of an abstract class. Doing this will raise a TypeError. You can create an abstract class using the abc module. To define an abstract method in Python, you use the @abstractmethod decorator.

Example:

Python

Output:

ABC Output 1
ABC Output 2

Explanation:

  • In this example, DataScienceCourse is a valid subclass of the abstract base class Course, as it has successfully implemented the get_duration() method. It prints 6 months without causing an error.
  • Then, we tried to instantiate an object of Course, the abstract class, but it threw an error.
  • Finally, PythonCourse became an invalid class since it did not implement the get_duration() method from the base class. This raised a TypeError in Error2.

Common Mistakes to Avoid in Inheritance in Python

Using inheritance can significantly enhance the power of your code, but it can also lead to some serious mistakes if you are not careful. Let us look at some of the common pitfalls in inheritance in Python.

  • Beginners usually call the parent class directly, which breaks flexibility, especially in multiple inheritance. It is recommended that you use the super() function instead. It makes your code resilient towards any future modifications.
  • Beginners might be overriding methods without calling the parent version first. If you want a method that extends the parent class, you must first call the parent version of that method before implementing the overriding lines of code.
  • Creating too many subclasses for every small variation can lead to a class explosion. It is a situation where your codebase becomes hard to maintain and understand due to a large number of class structures.

Real-World Example of Inheritance in Python

Intellipaat System

The following example models a real-world system like Intellipaat using inheritance. It demonstrates how various departments (like Technical Writing and Sales) and courses (like Full Stack Development) can be structured using single and multilevel inheritance in Python.

Example:

Python

Output:

Real World Example output

Explanation:

  • Intellipaat is the base class.
  • TechnicalWriter and the Sales classes inherit from the Employee class. They reuse attributes & methods like display(), org_info().
  • The FullStackCourse class inherits through multilevel inheritance. The inheritance follows this flow: Course → ProgrammingCourse → FullStackCourse.
  • All classes access shared org info from Intellipaat via the super() function.
Real-World Example Flow Diagram
Kickstart Your Coding Journey with Python – 100% Free
Learn the basics of Python through hands-on practice and projects.
quiz-icon

Conclusion

Inheritance is a powerful feature in Python for object-oriented programming that encourages reusability of the code, maintainable design, and promotes scalability. Different types of Inheritance include simple single inheritance, multiple inheritance, multilevel inheritance, and hierarchical inheritance. If you master how inheritance works, how super() function works with abstract base classes and overriding methods, you are on your way to creating reusable and maintainable systems with Python object-oriented programming. Whether you’re working on a small-scale application or a complex, multi-module system like the examples discussed in this blog, the techniques and best practices shared here will help you write better and more efficient Python code.

To take your skills to the next level, check out this Python Training course and gain hands-on experience. Also, prepare for job interviews with Python Interview Questions designed by industry experts.

Inheritance in Python – FAQs

Q1. What is the super() function and why is it important?

super() lets a child class access parent methods and properties without naming the parent, ensuring flexible, maintainable code and avoiding duplication, especially in complex inheritance structures.

Q2. How does Method Resolution Order (MRO) affect method calls in inheritance?

MRO determines the order Python searches for methods in parent classes, ensuring each method is called once and in the correct sequence, especially in multiple inheritance scenarios.

Q3. Can a child class override parent class methods?

Yes. A child class can redefine a parent’s method. Using super(), it can still call the original parent method if needed.

Q5. How does OOP make code reusable and maintainable in real-world systems?

OOP models real-world entities with classes and objects, reducing code duplication, improving organization, and making programs modular, easy to maintain, and scalable.

Q5. What is an abstract base class (ABC)?

An abstract base class (ABC) is a class that acts like a blueprint. It defines methods that its child classes must use, but you can’t create objects from it directly.

About the Author

Data Scientist | Technical Research Analyst - Analytics & Business Intelligence

Lithin Reddy is a Data Scientist and Technical Research Analyst with around 1.5 years of experience, specializing in Python, SQL, system design, and Power BI. Known for building robust, well-structured solutions and contributing clear, practical insights that address real-world development challenges.

EPGC Data Science Artificial Intelligence