Python Inheritance

In the last lesson, we learned about Python Methods. After learning about methods, let us learn about inheritance in Python. Inheritance lets us create new classes based on existing ones.

In this tutorial, we will learn what inheritance is, how to use it, and why it is useful.

๐ŸŒณ What Is Inheritance in Python?

Inheritance is a way to create a new class from an existing class. The new class gets all the attributes and methods of the existing class.

The existing class is called the parent class or base class. The new class is called the child class or derived class.

Think of it like this. A child inherits traits from their parents. Similarly, a child class inherits code from its parent class.

๐Ÿงฉ Why Do We Need Inheritance in Python?

Inheritance lets us reuse code. Instead of writing the same code again and again, we can put it in a parent class and reuse it in child classes.

It also makes our code more organized. We can group common features in a parent class and specific features in child classes.

๐Ÿ—๏ธ How to Create a Child Class in Python

We create a child class by putting the parent class name in parentheses.

class Animal:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating")
class Dog(Animal):
def bark(self):
print(f"{self.name} says Woof!")
dog = Dog("Buddy")
dog.eat()
dog.bark()

Output

Buddy is eating
Buddy says Woof!

Here, Dog inherits from Animal. So Dog gets the eat method and the __init__ method. And it adds its own bark method.

โš™๏ธ How to Override Methods in Python

A child class can override a method from the parent class. That means it provides its own version of the method.

class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()

Output

Woof!
Meow!

Both Dog and Cat override the speak method. So they behave differently.

๐Ÿ”ง How to Use super() in Python

Sometimes we want to call the parent class method from the child class. We use super() for that.

class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
dog = Dog("Buddy", "Labrador")
print(dog.name)
print(dog.breed)

Output

Buddy
Labrador

The super().__init__(name) calls the parent class constructor. That sets up the name attribute. Then the child class adds the breed attribute.

๐Ÿ’ก Types of Inheritance in Python

Python supports several types of inheritance.

Single inheritance โ€” One child class inherits from one parent class.

Multiple inheritance โ€” One child class inherits from multiple parent classes.

Multilevel inheritance โ€” A child class inherits from another child class.

Hierarchical inheritance โ€” Multiple child classes inherit from one parent class.

Hybrid inheritance โ€” A combination of the above.

We will focus on single inheritance for now. The others are more advanced.

๐Ÿงช A Real-Life Example โ€“ Vehicle Classes

class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start(self):
print(f"{self.brand} {self.model} is starting")
class Car(Vehicle):
def honk(self):
print("Beep beep!")
class Bike(Vehicle):
def ring(self):
print("Ring ring!")
car = Car("Toyota", "Corolla")
bike = Bike("Giant", "Escape")
car.start()
car.honk()
bike.start()
bike.ring()

Output

Toyota Corolla is starting
Beep beep!
Giant Escape is starting
Ring ring!

Both car and bike inherit from Vehicle. They get the start method. And they add their own methods.

๐Ÿ“Œ Common Mistakes with Inheritance in Python

โŒ Mistake 1: Forgetting to call super().init()

class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
self.breed = breed

This gives an error. Because name is not set.

Fix:

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed

๐Ÿšซ Mistake 2: Using the wrong parent class

class Dog(Cat):
pass

This works only if Cat is defined. Otherwise, it gives an error.

Fix: Make sure the parent class exists before using it.

๐Ÿ›‘ Mistake 3: Overriding without calling super()

class Dog(Animal):
def speak(self):
print("Woof!")

This overrides the parent method. If we want to add to it instead, we should call super().speak().

class Dog(Animal):
def speak(self):
super().speak()
print("Woof!")

Next, we will learn about Python Polymorphism and use one interface with different forms.