Python Inheritance: A Comprehensive Guide
Python was developed in the 1980s by Guido van Rossum as a successor to the ABC programming language. It has become extremely popular over the years and has more than 8 million Python developers at present. Python inheritance has been a fundamental feature of Python language since its inception. Its adoption of inheritance was driven by the goal of promoting modularity, extensibility, and code organization.
It empowers you to build complex systems by reusing existing code and extending its functionality. It is created to support the code configurability. Let’s take a deeper look into what is inheritance in Python, its syntax, types, advantages, and more.
What is Inheritance in Python?
We can define inheritance in Python as a strong characteristic of object-oriented programming that enables classes in Python to inherit properties and functions from other classes. The new class is called a derived class, and the present class is called a base class. The derived class acquires all of the characteristics and operations of the base class. It can also add its own properties and functions.
Inheritance enables programmers to develop a more productive and structured code by specifying general properties in a parent class and enhancing or focusing them in derived classes. In Python, inheritance plays an important role in constructing complicated software systems, supporting code sharing, and improving overall program structure. You can gain a better understanding of this subject through an online Python course.
Here is a demonstration of how inheritance operates in Python:
class Animal:
def eat(self):
print("I am eating.")
class Dog(Animal):
def bark(self):
print("Woof!")
# Creating an object of the Dog class
my_dog = Dog()
# Calling methods on the object
my_dog.eat() # Output: I am eating.
my_dog.bark() # Output: Woof!
Here, the Dog class inherits from the Animal class. This means that the Dog class has all of the characteristics and operations of the Animal class, containing the eat() method. The Dog class also has its own bark() method.
When you build an object of the Dog class, you can call the eat() and bark() operators on that object. The eat() method will print “I am eating”, and the bark() method will display “Woof!”.
Syntax of Inheritance
In Python, the syntax for executing inheritance requires specifying classes and applying the class identifier concurrently with the parentheses to demonstrate the base class from which the child class will receive. The syntax is as follows:
class ParentClass:
# Parent class attributes and methods
class ChildClass(ParentClass):
# Child class attributes and methods
Here, ParentClass is the name of the parent class, and ChildClass is the name of the child class. The child class is stated by referring to the parent class name in parentheses after the child class name (ChildClass(ParentClass)). The child class acquires all the properties and functions specified in the parent class, enabling code reuse and extension.
Types of Inheritance in Python
There are three kinds of inheritance in Python
Single Inheritance
It is also known as simple inheritance. In this type of inheritance, a single-child class is inherited from a single-parent class.
For example,
# Single inheritance
class ParentClass: # Base class
def method1(self):
print("Greetings from the ParentClass")
class ChildClass(ParentClass): # Derived class
def method2(self): # ParentClass is inherited in the ChildClass
print("Greetings from the ChildClass") # and used as a parameter in the ChildClass
# Driver Code
example = ChildClass() # Object instantiation
example.method1() # Invoking the method from the parent class through the child object
example.method2() # Invoking the method defined in the child class
Output:
Greetings from the ParentClass
Greetings from the ChildClass
Multiple Inheritance
In this type of inheritance, a child class is inherited from two or more parent class, which means that the child class will inherit methods and attributes of the parent classes.
For example,
#Multiple inheritance
class FirstParentClass: # First parent class
def method1(self):
print("Hello from the FirstParentClass")
class SecondParentClass: # Second parent class
def method2(self):
print("Hello from the SecondParentClass")
class ThirdParentClass: # Third parent class
def method2(self): # The method name matches that of SecondParentClass
print("Hello from the ThirdParentClass")
class ChildClass(FirstParentClass, SecondParentClass, ThirdParentClass): # Child class
def method3(self): # We incorporate the parent classes
print("Hello from the ChildClass") # as comma-separated arguments
# Driver Code
example = ChildClass() # Object instantiation
example.method1() # Invoking the method from FirstParentClass through the child object
example.method2() # Invoking the method from SecondParentClass through the child object
example.method3() # Invoking the method defined in the child class
# To determine the order in which classes are visited by the child class, we use __mro__ on the child class
print(ChildClass.__mro__)
Output:
Salutations from the FirstParentClass
Salutations from the SecondParentClass
Salutations from the ChildClass
(<class '__main__.ChildClass'>, <class '__main__.FirstParentClass'>, <class '__main__.SecondParentClass'>, <class '__main__.ThirdParentClass'>, <class 'object'>)
Multilevel Inheritance
In this type of inheritance, there is no single-parent class relationship. Every parent class is derived from another class. This means that every derived class (child class) becomes a parent class to another class.
For example,
#Multilevel Inheritance
class GrandparentClass: # First level
def method1(self):
print("Greetings from the Grandparent")
class ParentClass(GrandparentClass): # Second level
def method2(self):
print("Greetings from the Parent")
class ChildClass(ParentClass): # Third level
def method3(self):
print("Greetings from the Child")
# Driver Code
example = ChildClass() # Object instantiation
example.method1() # Third level invokes method from first level
example.method2() # Third level invokes method from second level
example.method3() # Third level invokes its own method
Output:
Greetings from the Grandparent
Greetings from the Parent
Greetings from the Child
Hierarchical Inheritance
In this type of inheritance, there are multiple derived classes from a single parent class. This inheritance is the reverse of multilevel inheritance.
For example,
# Hierarchical inheritance
class ParentClass: # Base class
def method1(self):
print("Greetings from the ParentClass")
class FirstChildClass(ParentClass): # First child class
def method2(self):
print("Greetings from the FirstChildClass")
class SecondChildClass(ParentClass): # Second child class
def method3(self):
print("Greetings from the SecondChildClass")
# Driver Code
example1 = FirstChildClass() # Object instantiation for the first child
example2 = SecondChildClass() # Object instantiation for the second child
example1.method1() # Invoking the method from the parent class via the first child object
example1.method2() # Invoking the method defined in the first child class
example2.method1() # Invoking the method from the parent class via the second child object
example2.method3() # Invoking the method defined in the second child class
Output:
Greetings from the ParentClass
Greetings from the FirstChildClass
Greetings from the ParentClass
Greetings from the SecondChildClass
Hybrid Inheritance
- As the term suggests, this type of inheritance is a combination of two or more types of inheritance in Python. This tells that there will be multiple as well as multilevel relationships between parent and child classes.
For example,
# Hybrid inheritance
class FirstParentClass: # First parent class
def method1(self):
print("Greetings from the FirstParentClass")
class SecondParentClass: # Second parent class
def method2(self):
print("Greetings from the SecondParentClass")
class FirstChildClass(FirstParentClass): # First child class
def method3(self):
print("Greetings from the FirstChildClass")
class SecondChildClass(FirstChildClass, SecondParentClass): # Second child class
def method4(self):
print("Greetings from the SecondChildClass")
# Driver Code
example1 = FirstChildClass() # Object creation for the first child
example2 = SecondChildClass() # Object creation for the second child
example1.method1() # FirstParentClass Method Invoked via first child object
example1.method3() # Invoking method from FirstChildClass
example2.method1() # FirstParentClass Method Invoked via second child object
example2.method2() # SecondParentClass Method Invoked via second child object
example2.method3() # FirstChildClass Method Invoked via second child object
example2.method4() # Invoking method defined in SecondChildClass
Output:
Greetings from the FirstParentClass
Greetings from the FirstChildClass
Greetings from the FirstParentClass
Greetings from the SecondParentClass
Greetings from the FirstChildClass
Greetings from the SecondChildClass
Use Case of Inheritance in Python
Python inheritance has various use cases across software development. Here are a few common scenarios where inheritance is beneficial:
Code Reusability
Inheritance allows developers to reuse code from parent classes in derived classes. This promotes code reusability and reduces redundancy. For example, a base class defining generic database operations can be inherited by specific derived classes for different types of databases.
Modularity and Organization
Inheritance helps in creating modular and organized code structures. It allows developers to define a base class with common attributes and methods, and then derive specialized classes from it. This promotes code organization and logical grouping of functionality.
Polymorphism
Inheritance enables polymorphism in python, where objects of different classes can be treated uniformly through a common interface. This facilitates writing more flexible and adaptable code that can work with different types of objects.
For example,
#Python function to demonstrate Polymorphism
def perform_addition(a, b, c = 0):
return a + b+ c
# Driver code
print(perform_addition(3, 4))
print(perform_addition(3, 4, 5))
Output:
7
12
Extending Functionality
Derived classes can extend the functionality of the base class by adding new attributes and methods. This allows developers to build upon existing code and create specialized classes with additional features or behavior.
Frameworks and Libraries
Inheritance is widely used in frameworks and python libraries to provide customizable functionality. Developers can inherit from predefined classes in the framework or library and override or extend their methods to suit their specific needs.
Advantages and Disadvantages of Python Inheritance
The following is a list of the advantages and disadvantages of Python inheritance.
Advantage | Disadvantage |
---|---|
It is used for code reusability. | It can lead to tight coupling. |
It is used for creating modular code. | It can increase code complexity. |
It is used for extending functionality. | It can result in the diamond problem. |
It is used for achieving polymorphism. It can limit flexibility in code design. | It can limit flexibility in code. |
It is used for easy code maintenance. | It can make the base class fragile. |
Conclusion
Python inheritance offers a valuable tool for code organization, reusability, and extensibility. In this blog, we discussed the concept of inheritance, its types, syntax, and more. Overall, understanding and effectively using inheritance can significantly improve the code structure and promote efficient development practices.
FAQs
The __init__ method is only used within classes in Python. This function is invoked each time an object is created from a class. Its main function is to initialize the attributes of the object being created.
The following are the five types of inheritance in Python.
Single Inheritance
Multiple Inheritance
Hybrid Inheritance
Multilevel Inheritance
Hierarchical Inheritance
The disadvantages of inheritance in Python are:
a) Since classes are inherited from one class to another, they are interdependent. This means that the execution speed of running the code decreases.
b) Child classes cannot be executed independently without defining the parent class in the code.
The super() function enables a child class or derived class to inherit all the methods and attributes of the parent class.