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:

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.


POSTGRADUATE PROGRAM IN
Multi Cloud Architecture & DevOps
Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.
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:

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

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:

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

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:

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.


82.9%
of professionals don't believe their degree can help them get ahead at work.
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:

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
- Code Reusability
- We can reuse existing code without rewriting it.
- This saves time and effort.
- Improved Readability and Maintainability
- Code is easier to read and manage.
- Changes made in a parent class reflect in all child classes.
- Reduced Redundancy
- No need to duplicate code.
- Common features are centralized in a base class.
- Consistent Interfaces
- Methods and attributes are consistent across classes.
- This ensures a standardized approach to coding.
Disadvantages of Using Inheritance in Python
- Decreased Execution Speed
- Loading multiple classes can slow down execution.
- This is due to the interdependence of classes.
- Tight Coupling
- Classes become tightly coupled.
- Changes in the parent class can affect all child classes.
- 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.
Can a child class inherit from multiple parent classes in Python?
What is the difference between single and multilevel inheritance?
What are the potential drawbacks of using inheritance in Python?
Updated on August 6, 2024
