Types of Inheritance in Python (With Examples)

Updated on August 6, 2024

Article Outline

Have you ever wondered how to reuse code without rewriting it every time? That’s where inheritance in Python comes in handy. Inheritance allows us to create a new class from an existing class. It saves time and makes our code more efficient.

 

Why should we care about inheritance? Here are some reasons:

 

  • We don’t need to write the same code again.
  • Our code is easier to read and maintain.
  • We save time by building on existing code.

 

The process by which the properties of the base (parent) class are passed down to the child class is known as inheritance. It’s like inheriting traits from our parents. We can use these inherited features to build complex systems with ease.

 

There are four types of inheritance in Python:

 

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance

 

Let’s dive into the details with simple examples.

 

Also Read: Python Tutorial for Beginners

Detailed Explanation of Single Inheritance with Examples

Single inheritance can be considered the simplest among all the types of inheritance in Python. A child class inherits from one parent class. Let’s see how this works.

Example:

class Animal: def sound(self): return "Some generic sound" class Dog(Animal): def sound(self): return "Bark" def main(): pet = Dog() print(pet.sound()) if __name__ == "__main__": main()

Output:

output1

Here, the Dog class inherits from the Animal class. The Dog class uses the sound method from Animal but overrides it with its own version.

single inheritance

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Understanding Multiple Inheritance Through Unique Examples

Multiple inheritance means a class inherits from more than one parent class. This can be powerful but tricky. Let’s see how it works.

Example:

class Flyer: def action(self): return "I can fly" class Swimmer: def action(self): return "I can swim" class Duck(Flyer, Swimmer): def action(self): return f"{Flyer.action(self)} and {Swimmer.action(self)}" def main(): bird = Duck() print(bird.action()) if __name__ == "__main__": main()

Output:
output2

In this example, Duck inherits from both Flyer and Swimmer. It uses the action methods from both parent classes.

Multiple Inheritance

Using multiple inheritance can be tricky, but it’s very powerful when used correctly. Here are some key points to remember when dealing with multiple inheritance:

  • Python follows the Method Resolution Order (MRO). It means the order in which parent classes are listed matters.
  • Make sure parent classes don’t have methods with the same name. If they do, Python uses the method from the first parent class listed.

Exploring Multilevel Inheritance in Python with Code Samples

Ever felt stuck on how to connect different levels of inheritance? Let’s break down multilevel inheritance. These types of inheritance in Python involve a parent class, a child class, and a grandchild class.

Example:

class Vehicle: def __init__(self, make): self.make = make def info(self): return f"This is a vehicle made by {self.make}" class Car(Vehicle): def __init__(self, make, model): super().__init__(make) self.model = model def info(self): return f"{super().info()}, model: {self.model}" class ElectricCar(Car): def __init__(self, make, model, battery_capacity): super().__init__(make, model) self.battery_capacity = battery_capacity def info(self): return f"{super().info()}, with a battery capacity of {self.battery_capacity} kWh" def main(): tesla = ElectricCar("Tesla", "Model S", 100) print(tesla.info()) if __name__ == "__main__": main()

Output:

output3

Here, ElectricCar inherits from Car, which in turn inherits from Vehicle. This creates a chain of inheritance. Each class builds upon the previous one.

Multilevel Inheritance

Comprehensive Guide to Hierarchical Inheritance with Practical Illustrations

How do we manage multiple child classes from a single parent? That’s hierarchical inheritance. It allows a parent class to have multiple child classes.

Example:

class Tree: def type(self): return "This is a tree" class Oak(Tree): def type(self): return f"{super().type()} -> This is an oak tree" class Pine(Tree): def type(self): return f"{super().type()} -> This is a pine tree" def main(): oak_tree = Oak() pine_tree = Pine() print(oak_tree.type()) print(pine_tree.type()) if __name__ == "__main__": main()

Output:
output4

In this example, Oak and Pine both inherit from Tree. Each child class has its own unique type method while still using the parent class method.

Hierarchical inheritance

 

Hybrid Inheritance in Python: Combining Different Inheritance Types

Wondering how to mix different inheritance types? Hybrid inheritance combines multiple inheritance forms. It creates a complex but flexible structure.

Example:

class Organism: def trait(self): return "This is a living organism" class Plant(Organism): def trait(self): return f"{super().trait()} -> This is a plant" class Animal(Organism): def trait(self): return f"{super().trait()} -> This is an animal" class VenusFlytrap(Plant, Animal): def trait(self): return f"{super().trait()} -> This is a carnivorous plant" def main(): flytrap = VenusFlytrap() print(flytrap.trait()) if __name__ == "__main__": main()

Output:

output5

Here, VenusFlytrap inherits from both Plant and Animal. It uses traits from both parent classes.

 

Also Read: How to Learn Python Language from Scratch

Advantages and Disadvantages of Using Inheritance

We have covered all four types of inheritance in Python with detailed examples. Are you wondering if inheritance in Python is worth the trouble? Let’s break it down.

Advantages of Using Inheritance in Python

 

  1. Code Reusability
  • We can reuse existing code without rewriting it.
  • This saves time and effort.

 

  1. Improved Readability and Maintainability
  • Code is easier to read and manage.
  • Changes made in a parent class reflect in all child classes.

 

  1. Reduced Redundancy
  • No need to duplicate code.
  • Common features are centralized in a base class.

 

  1. Consistent Interfaces
  • Methods and attributes are consistent across classes.
  • This ensures a standardized approach to coding.

Disadvantages of Using Inheritance in Python

  1. Decreased Execution Speed
  • Loading multiple classes can slow down execution.
  • This is due to the interdependence of classes.

 

  1. Tight Coupling
  • Classes become tightly coupled.
  • Changes in the parent class can affect all child classes.

 

  1. Complexity in Hierarchies
  • Complex hierarchies can be hard to understand.
  • It requires careful planning to avoid confusion.

Conclusion

Inheritance is a powerful tool in Python. It helps us build efficient, readable, and maintainable code. By reusing code, we save time and reduce errors. But, we must be mindful of its disadvantages like tight coupling and potential complexity. Choosing the right type of inheritance based on the situation is key. Keep experimenting and applying these concepts to improve your Python skills.

FAQs
Indeed, this is what is termed as multiple inheritance. It is possible for a child class to implement attributes and methods of more than one parent class.
Single inheritance is a process where the new class known as child class is derived from only one existing or parent class. Multiple inheritance on the other hand is when a child class will be a direct sub-class of another class that is a sub-class of yet another class hence creating a hierarchy of the sub-classes.
Inheritance implies a tight coupling between classes, which can possibly reduce execution speed when more than one class has been loaded.

Updated on August 6, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved