A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://intellipaat.com/blog/python-inheritance/ below:

Python Inheritance (with Examples)

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) is a programming method where we organize code using classes and objects. It helps keep the code clean, reusable, and easier to understand by grouping related data and functions. Imagine you have to write code to define a real-world system based on an EdTech company. This company has many departments, such as HR, Sales, Technical Writing, and a Design Team. It offers multiple courses across various disciplines, such as Cyber Security, Artificial Intelligence, Data Science, and more. Each department has its roles and responsibilities, but they all function under a base class called EdTechCompany.

Now, if you had to represent this structure using code, you would have to manually define every department and course separately. Writing out all the shared information manually would make the code long, repetitive, and hard to maintain. It would also take a lot of time to write. This is where object-oriented programming (OOP) in Python becomes powerful.

With OOP, you can create structured, reusable blocks of code with ease that represent real-world entities like ‘Employee’ or ‘Course’. This technique will not only reduce the length of the code but also make it more organised, modular, and easier to understand.

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

To Learn More about Inheritance and Advance Your Career with Python - Sign up now!

Expert-led. Project-based. Certificate included.

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:

Output:

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

Understanding the 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

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.

How to Create a Child Class in Python

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.

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

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.

What is the super() Function in Python and Why Is It Important?

When working with inheritance in Python, you’ll often want to call methods from the parent class while writing code in the child class. This is where the super() function comes in.

The super() function is a shortcut that gives you access to methods and properties from the parent class without having to name the parent. The super() keyword refers to the parent class directly. This function saves you from writing the entire method again.

Method Resolution Order (MRO)

When using super(), Python has to know which parent class’s method to call if the inheritance is not linear. Python relies on a system called Method Resolution Order (MRO), which describes the order in which classes are searched for methods. MRO guarantees that methods will be found and called exactly once and in the correct order. You can use the .mro() method to see the MRO of a class.

Example:

Let us update our TechnicalWriter class from earlier and use super() to call the constructor of the Employee class.

Output:

Explanation:

Benefits of Using the super() Function in Python OOP

You must be wondering what overridden methods are. In simple terms, an overridden method is a method in a child class that replaces or redefines a method that was inherited from a parent class. Let us understand it in more detail in the next subsection.

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.

Output:

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.

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:

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.

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:

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

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:

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.

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:

Output:

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

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:

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.

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:

Output:

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

Composition

Example:

Output:

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.

Abstract Base Classes(ABCs) in Python

An Abstract Base Class is 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:

Output:

Explanation:

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.

Real-World Example:

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:

Output:

Explanation:

Kickstart Your Coding Journey with Python – 100% Free

Learn the basics of Python through hands-on practice and projects.

Conclusion

Inheritance is a powerful feature in Python for object-oriented programming that encourages reusability of the code, maintainable design, and also 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 inheritance in Python?

Inheritance allows a class (child) to inherit attributes and methods from another class (parent).

Q2. What are the types of inheritance in Python?

Python supports single, multilevel, multiple, hierarchical, and hybrid inheritance.

Q3. What is the use of the super() function?

The super() function allows you to call methods from the parent class without explicitly naming it.

Q4. Can a child class override parent class methods?

Yes, child classes can redefine or override methods inherited from the parent.

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.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4