Types of Inheritance in Python (with Examples)

Types of Inheritance in Python

Do you want to clarify your concept of Python inheritance? Well, then, you have found the right place! In this article, we will have an in-depth conversation about everything related to Python inheritance.

Python is an Object-Oriented language, and inheritance is one of its key concepts. It is the process where one class acquires the properties or features of the other which ultimately helps in better memory utilization.

If you feel stuck and need some help clarifying your concepts, leave a comment or reach out to our Python experts. We are always available to help you!

Let’s get to know about the Python inheritance concept right away!

Summary Of The Article:

  • Inheritance In Python occurs when a child class inherits the parent class’s properties and attributes.

  • In the Python inheritance syntax, you have to write the parent class name in parenthesis after the child class name to declare a child class name.

  • There are 5 main types of inheritance in the Python language – Single, Multiple, Multilevel, Hierarchical, and Hybrid.

  • Inheritance allows us to reuse code and make the same code more organized by extending different class’s functionalities.

An Introduction To Python Inheritance

Inheritance in Python is one of the pillars of Object-oriented programming. It allows one class to inherit or derive the features or properties of the other class.

The class which derives the properties is known as the derived class or child class. The class whose properties are inherited is known as the base class or parent class.

Let us understand this with the help of an example. Consider a program that has an animal class. This class has different attributes like species, habitat, etc. Now, you can also have different classes like the class dog, or cat that can inherit specific attributes from the animal class.

We will have a look at it with a code example in the later sections of the article. It is important to note that there can be multiple child classes for a particular parent class. It is also possible to have multiple parent classes for one child class.

Inheritance allows us to organize our code and streamline it by defining a hierarchical structure of classes and objects. It also promotes code reusability.

What Are The Key Concepts Of Inheritance? Read Below

Before diving into the types of inheritance in Python, let us go through some of its key concepts. These will help us understand the purpose and implementation of Python inheritance. There are 3 main things that you should know about –

Parent class or base class:

The base class or the parent class is the one whose attributes get inherited by another class. These attributes can be variables or functions that identify or define an object’s behavior. The methods defined in the parent class can be directly accessible in the child class.

Have a look at the example code given below to get an idea.

				
					# Parent Class (Base Class)
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return f"{self.name} makes a sound."
				
			

In the above example, we have an Animal class with an attribute name and the method speak(). If we use this as a parent class, the child class will directly be able to inherit the name and speak() attributes of this class.

Child class or derived class:

The child class or the derived class is a class that inherits the properties or attributes of the parent class or the base class. Inheritance in Python allows the child class to access the methods and attributes of the parent class for performing operations.

A child class can also create its methods and attributes. It can also modify or override methods of the parent class to provide a specific behavior.

Take a look at the code below:

				
					# Child Class (Derived Class)
class Dog(Animal):
    def speak(self):
        return f"{self.name} barks."
				
			

In the above snippet, the class dog is the child class having the Animal class as its parent class. The parent class can be represented in parenthesis while defining the child class.

Object class:

The object class is the root class of all the classes in your Python program. It’s the parent class from which all the other classes inherit either directly or indirectly.

It has some universal methods like __init__, __str__, or __eq__ We can apply these standard methods to all objects in Python. A simple code example is given below.

				
					# Explicitly inheriting from Object Class
class Person(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f"Person: {self.name}"
				
			

In the above example, the Person class is inherited from the object class explicitly. However, it is not required to explicitly inherit from it in Python 3, as it is a default functionality in this version.

Let’s move further and finally discuss the types of Python inheritance with the help of examples. Keep reading to learn more!

Understand Different Types Of Python Inheritance With Examples

Python is an object-oriented programming language that writes its code in the form of Python classes and objects. We already know about the basic terminologies of Python inheritance like Parent class, child class, objects, attributes, etc.

Now, it is time to finally see how we can use class inheritance in our Python program. The following are the types of inheritance in Python.

  • Single Inheritance

  • Multiple Inheritance

  • Multi-level Inheritance

  • Hierarchical Inheritance

  • Hybrid Inheritance

So, let us start discussing the types of Python inheritance in detail with the help of code examples to gain a piece of better knowledge. Read below to know!

-> Single Inheritance

It is also known as simple inheritance. In this type of Python inheritance. One child class derives the attributes of a single-parent class only. Let us take the example of the animal class and its child class dog to see how it works.

The code for the same is given below.

				
					# Parent Class (Base Class)
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        return f"{self.name} makes a sound."

# Child Class (Derived Class)
class Dog(Animal):
    def speak(self):
        return f"{self.name} barks."
    
# Creating Objects
dog = Dog("Buddy")
print(dog.speak())  
				
			

Program Explanation:

  • We have an Animal class that has a name attribute and the speak() method.

  • We have created the class Dog that extends the functionality of its parent class i.e. Animal.

  • The object that will be created will be of the child class.

  • When we call the method speak() it overrides the speak() method of the parent class and the function returns the content of the speak() method of the child class.

Output:

Single Inheritance Code Output

From the above output, it is clear that the statement from the class Dog was printed instead of the statement in the class Animal. Thus, this is how the single inheritance takes place.

-> Multiple Inheritance

In multiple inheritance, one child class can have multiple parent classes. This kind of inheritance is useful when you need to combine the functionalities from different sources.

Let us consider an example where the class employee is the child class that has Company class and Person class as the multiple base classes. The employee class can inherit attributes from both of these classes.

The Python program for the same is given below. Have a look at it to understand the implementation.

				
					# Parent class 1
class Person:
    def __init__(self, name):
        self.name = name

    def introduction(self):
        return f"My name is {self.name}."

# Parent class 2
class Company:
    def __init__(self, company_name):
        self.company_name = company_name

    def company_info(self):
        return f"I work at {self.company_name}."

# Child class
class Employee(Person, Company):
    def __init__(self, name, company_name, role):
        Person.__init__(self, name)
        Company.__init__(self, company_name)
        self.role = role

    def job_info(self):
        return f"I work as a {self.role}."

# Creating an object of the employee class
employee = Employee("Alice", "CodingZap", "Programming Expert")

print(employee.introduction())   
print(employee.company_info()) 
print(employee.job_info())     
				
			

Program Explanation:

  • In the above example, we have the Person class and the Company class which are the parent classes for class Employee.

  • Each class has its method. For instance, the Person class has the introduction() method, the Company has the company_info() method, and the Employee has the job_info() method in the class definitions.

  • We have to create an object for the child class and call for functions.

  • In the child class, when the introduction() and company_info() methods are invoked, each function from the parent class is executed.

  • This way, we are combining all the methods of multiple parent classes with the derived classes.

Output:

Multiple Inheritance Code Output

It is seen that the child class inherits the features of both the parent classes, which is why we were able to access each method from the parent class in multiple inheritance.

-> Multi-level Inheritance

Multilevel Inheritance is like a chain of inheritance. Think of it like inheriting genes from your previous generations. You inherit your parent’s genes who have inherited their genes from their parents.

Again, let us take an example where we have ‘Animal’ as the parent class, ‘Dog’ class as its child, and finally puppy class as the child class of the dog class. The code for the same is given below.

				
					# Parent class
class Animal:
    def eat(self):
        return "Animal eats."

# Intermediate child class
class Dog(Animal):
    def bark(self):
        return "Dog barks!"

# Final child class
class Puppy(Dog):
    def sleep(self):
        return "Puppy sleeps peacefully!"

# Creating an object
puppy = Puppy()

print(puppy.eat()) 
print(puppy.bark())    
print(puppy.sleep())     
				
			

Program Explanation:

  • We have created an object of the Puppy class that also has access to the other methods of the two classes above it.

  • We can call the other methods because of the multilevel inheritance.

  • Thus, when we call the eat() and bark() methods using the same object, we can get an output.

Output:

Multi-level Inheritance Code Output

We can execute the method sleep() and other methods of the above example using the inheritance concept. Thus enhancing code reusability.

-> Hierarchical Inheritance

In this type of inheritance, one or more child classes inherit properties from a single-parent class. It is just like having a sibling! Each child class inherits all the methods and attributes from the parent class.

Let us understand this with the help of a Python code example. Have a look to learn more!

				
					# Parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def eat(self):
        return f"{self.name} is eating."

# Child class 1
class Dog(Animal):
    def bark(self):
        return f"{self.name} says: Woof!"

# Child class 2
class Cat(Animal):
    def meow(self):
        return f"{self.name} says: Meow!"

# Creating objects
dog = Dog("Buddy")
cat = Cat("Kitty")

print(dog.eat())  
print(dog.bark())  
print(cat.eat())   
print(cat.meow())  
				
			

Program Explanation:

  • In the above example, we have only one parent class with the class name Animal’

  • This parent class has the name attribute and the eat() method defined in it.

  • We have created two classes that act as the child class for the Animal class.

  • One of these is the Dog class that we have already seen in the previous examples. The other one is a new-class Cat.

  • Each child class inherits all the methods and instance variables from the parent class in this example.

  • We will also create objects for the two classes and call the methods for each object.

  • The parent method will also be called for each class child in the example.

Output:

Hierarchical Inheritance Code Output

There is only one parent class in the example and for the object of the dog class, the parent method prints the name attribute as ‘Buddy’, and for the new object of the new class, Cat, the parent class method prints the name attribute as ‘Kitty.’ Other methods of the dog class and the cat class are printed as expected.

-> Hybrid Inheritance

Hybrid inheritance in Python occurs when more than one form of class inheritance is combined. Hybrid inheritance often leads to conflicts like the diamond problem as more than one form of inheritance is involved.

To solve this conflict, Python uses the Method Resolution Order (MRO) Every object in Python has the __mro__ attribute.

The following code represents an example of this type of inheritance. Here, we have combined the multiple and multi-level inheritance.

				
					# Base class
class Animal:
    def breathe(self):
        return "Animal is breathing."

# Intermediate classes
class Mammal(Animal):
    def give_birth(self):
        return "Mammal gives birth to live young."

class Bird(Animal):
    def fly(self):
        return "Bird flies in the sky."

# Derived class
class Bat(Mammal, Bird):
    def nocturnal(self):
        return "Bat is active at night."

# Creating an object
bat = Bat()

print(bat.breathe())      
print(bat.give_birth())   
print(bat.fly())          
print(bat.nocturnal())  
				
			

Program Explanation:

  • We have a parent class named Animal.

  • It has two child classes – Mammal and Bird. Each child class inherits all the properties of the Animal class.

  • Finally, we have class Bat, which is the child class of two-parent classes – Mammal and Bird.

  • We then created a new object for the Bat class and called the methods for each existing class.

Output:

Hybrid Inheritance Code Output

From the above example output, we can see that we have successfully achieved inheritance in Python. However, it is important to note that if the methods had the same name or if the same method existed in each existing class, we could’ve encountered an error.

This kind of situation is called the diamond problem. To do this, we use method overriding in Python.

Now that we have covered all the types of Python inheritance and understood the Python inheritance syntax, let us discuss some of the pros and cons of the Inheritance concept in Python programming.

Advantages And Disadvantages Of Python Inheritance

Below are some of the advantages and disadvantages of Inheritance. Let’s examine these to better understand the concept.

Pros

Cons

It allows us to use the same elements of the code multiple times. Hence, adding code reusability.

Deep inheritance can lead to the code being complex.

It offers modularity by breaking down the code in the form of parent class and child class.

Changes in the parent class can affect the changes in the child class.

The child class inherits the data members and methods of another class easily by extending the parent class.

Accidental method overriding may occur as the same method may be present in multiple classes.

The use of the built-in function super() allows the child class to automatically inherit and easily call methods of the parent class.

Inheritance may lead to potential overengineering.

Run-time polymorphism can be achieved using method overriding.

Determining the MRO in multiple parent classes may be complex.

Conclusion:

I hope that by now you have understood the types of Python Inheritance and how to implement them. The syntax for designing parent classes and child classes is extremely easy. You just have to make sure the parent class name is in brackets after the child class.

It is also how you can identify if inheritance is taking place in a code that you are reading for the first time. Different types of inheritance are useful in different ways. We can override the same method from the parent class if it is already in the child class.

However, for all of these, you should have a sound understanding of the Python Basics.

So, if youโ€™re also looking to clear your Python Basics then you can always hire CodinngZap experts.

Additionally, considerย hiring Python tutorsย to accelerate your learning journey and gain personalized guidance along the way.

Takeaways:

  • Inheritance is a way in which a child class inherits the attributes from the other class and extends its functionality.

  • There are 5 major types of Python inheritance and each of them can be combined as per the requirements of the program.

  • You can use the special method super() that helps the child class automatically inherit properties from its parent class without using the parent class name in its definition.

  • The same method can be present in both the parent and the child class. Use method overriding to choose which function you need to call.

Leave a Comment

Your email address will not be published. Required fields are marked *