Inheritance in Python: Building Better Code with Classes
What is Inheritance?
Inheritance in programming is a bit like genetics in humans. Just as children inherit certain traits from their parents, in programming, a new class can inherit all the characteristics and abilities from another class. It’s like passing on the family traits but for code!
Still not getting it? No worries
Imagine you have a magic notebook that can do different things, like drawing, writing, and calculating. Now, you want to create a new magic notebook that can do all the same things as the first one but also play music.
Inheritance in programming is like making that new magic notebook. You start with the first notebook, which already knows how to draw, write, and calculate. Then, you add a new ability to play music. So, your new notebook can do everything the first one can, plus play music.
It’s like taking something you already have, making it even cooler, and using it in your new project. That’s what inheritance does in programming
How Does Inheritance Work in Python
In Python, you can define inheritance using the following syntax:
class BaseClass:
# attributes and methods of the base class
class SubClass(BaseClass):
# additional attributes and methods specific to the subclassBase Class: also called a parent class or superclass This class contains attributes and methods that you want to share with other classes.
SubClass: also called a derived class or child class. is like a special class that gets stuff from another class, called BaseClass. class SubClass(BaseClass):, and it means SubClass can use things from BaseClass. It’s like getting superpowers from BaseClass!
Here’s an example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # This method will be overridden in the derived class
class Cat(Animal):
def speak(self):
return f"{self.name} says Maaw!"
# Create instances of the derived class (Cat)
my_cat = Cat("Lucy")
# Use the overridden method from the derived class (Cat)
print(my_cat.speak())Output : Lucy says Maaw!
In this example we have two classe ‘Animal’ and ‘Cat’
- animal: I’ts the base class like a basic animal with a name, but it doesn’t know how to speak yet. It has an
__init__method to set the name and aspeakmethod that does nothing (it's waiting to be customized). - Cat: It’s a type of animal (a subclass of
Animal). It also has an__init__method inherited fromAnimal, so it can set the name. But, it overrides thespeakmethod to make the cat say "Maaw!"
- We create an instance of the
Catclass namedmy_cat(even though it's a cat). It's given the name "Lucy." - We call the
speakmethod onmy_cat, and since it's a cat and not just any animal, it knows how to speak like a cat. So, it returns "Lucy says Maaw!”
Inheritance Functions
super() Function
The super() function in Python is like a magic bridge between a child and a parent. It helps the child class communicate with and borrow things from the parent class. It's like saying, "Hey parent, give me your special powers," and the parent says, "Sure, here you go!" It allows you to access and use methods and attributes from the parent class in the child class, making your code more powerful and organized.
Her’s an example
Imagine you have a special kind of car, let’s call it a “SuperCar”, and you want to make it do some cool things. You already have a basic car, which we’ll call the “BaseCar”, that has some basic functions like driving and honking the horn.
Now, you want your SuperCar to inherit all the abilities of the BaseCar (because every SuperCar is also a BaseCar), but you also want to add some extra cool features to it, like a turbo boost.
Here’s where the super() function comes into play:
Get oussam laamri’s stories in your inbox
Join Medium for free to get updates from this writer.
Creating the SuperCar class: First, you create a class for your SuperCar. Inside this class, you use super() to call methods from the BaseCar class.
class BaseCar:
def drive(self):
print("BaseCar is driving")
def honk_horn(self):
print("Honk! Honk!")
class SuperCar(BaseCar):
def drive(self):
super().drive() # This calls the drive method from the BaseCar class.
print("SuperCar is driving really fast with a turbo boost!")
def use_turbo_boost(self):
print("Turbo boost activated!")- You create a SuperCar class that inherits from the BaseCar class using
class SuperCar(BaseCar). - Inside the SuperCar class, you override the
drive()method. When you callsuper().drive(), it means you want to use thedrive()method from the BaseCar class first, and then you add some extra behavior to it. - You also add a new method called
use_turbo_boost()which is specific to SuperCars.
Now, when you create a SuperCar object and call its methods:
my_supercar = SuperCar()
my_supercar.drive()
my_supercar.use_turbo_boost()output:
BaseCar is driving
SuperCar is driving really fast with a turbo boost!
Turbo boost activated!
So, in a nutshell, the super() function helps you access and use methods from the parent (or base) class when you're working with inheritance in Python.
Another functions:
isinstance():
Purpose: Checks if an object belongs to a specific class.
Syntax:isinstance(object, class).
Usage: Useful for type-checking before performing class-specific operations.issubclass():
Purpose: Checks if one class is based on another class (if it’s a subclass).
Syntax:issubclass(class, superclass).
Usage: Helps determine class relationships and hierarchies.type():
Purpose: Finds out the type (class) of an object.
Syntax:type(object)ortype(object) is class.
Usage: Basic type checking, less precise for inheritance checks.
Multiple Inheritance
Imagine you have different classes that represent different things. Multiple inheritance allows you to create a new class that inherits from more than one of these classes. It’s like combining the features of those classes into one new class.
Her’s an example:
You have a class called “Vehicle” with methods like “move” and “stop”.
also have a class called “Animal” with methods like “eat” and “sleep”.
Now, you want to create a new class called “Leopard” that can both “move” like a vehicle and “eat” like an animal. With multiple inheritance, you can make the “Leopard” class inherit from both “Vehicle” and “Animal,” so it can do both things.
class Vehicle:
def move(self):
print("can started like vehicle")
def stop(self):
print("can stopped like Vehicle")
class Animal:
def eat(self):
print("Animal eating")
class Leopard(Vehicle, Animal):
pass
Leopard = Leopard()
Leopard.move() # Output: "can started like vehicle"
Leopard.eat() # Output: "Animal eating"In this example, the “Leopard” class inherits from both “Vehicle” and “Animal,” so it can use methods from both parent classes. That’s the essence of multiple inheritance — combining features from different classes to create a new class with a mix of behaviours.
Some resources to understand concepts and examples in inheritance
Avanced resources (Videos)
(6408) Python OOP Tutorial 4: Inheritance — Creating Subclasses — YouTube
Learn to Program 10 : Inheritance Magic Methods — YouTube
Normal resources (Videos)
(6408) Python inheritance 👪 — YouTube
Python super function 🦸 — YouTube
Articles
Inheritance in Python (Guide) — PYnative
Inheritance in Python (With Examples) — Python Tutorial (pythonbasics.org)








