Understanding Inheritance in Python
Python is known for its clean syntax and powerful object-oriented programming (OOP) capabilities. One of the core pillars of OOP is inheritance, a concept that allows you to build new classes based on existing ones.
- What is Inheritance?
Inheritance allows one class (called the child or subclass) to inherit the properties and behaviors (methods and attributes) of another class (called the parent or superclass).
This makes it easier to reuse code and build a more hierarchical structure in our application.
2. Why Use Inheritance?
Imagine we’re building a game with different types of characters — like a Warrior, a Mage, and a Healer. All of them have some shared features like name, health, and attack().
Rather than defining these features separately in every class, we can define them once in a base class (Character) and then have the other classes inherit from it.
Syntax of Inheritance
Get Neesha Basnet’s stories in your inbox
Join Medium for free to get updates from this writer.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks."
class Cat(Animal):
def speak(self):
return f"{self.name} meows."Note:
- Dog and Cat inherit from Animal.
- They override the speak() method with their own implementation.
* Using super() to Access the Parent
Sometimes, you’ll want to use methods from the parent class within the child class. That’s where super() comes in handy.
class Bird(Animal):
def speak(self):
parent_sound = super().speak()
return f"{parent_sound} But specifically, {self.name} chirps."Types of Inheritance in Python
Python supports several types of inheritance:
- Single Inheritance — One child class inherits from one parent class.
- Multiple Inheritance — A child class inherits from more than one parent class.
- Multilevel Inheritance — A child class inherits from a class that itself inherited from another class.
- Hierarchical Inheritance — Multiple child classes inherit from the same parent class.
Here’s an example of multiple inheritance:
class Flyer:
def fly(self):
return "Flying high"
class Swimmer:
def swim(self):
return "Swimming fast"
class Duck(Flyer, Swimmer):
pass
d = Duck()
print(d.fly()) # Output: Flying high
print(d.swim()) # Output: Swimming fastInheritance is a powerful tool in Python, helping us write cleaner, DRY (Don’t Repeat Yourself), and more organized code. Understanding how and when to use it will level up your programming game, especially when dealing with large, complex systems.








