Inheritance in Python

python inheritance tutorial
10 November 2024

Understanding Inheritance in Python

Inheritance is one of the fundamental concepts in object-oriented programming. By using inheritance, you can define new classes based on the characteristics and behaviors of existing classes, allowing you to re-use your code. In Python, defining inheritance is very straightforward; in this way, the class inherits properties and methods defined in the parent class.

Next, we will review a simple example to better understand how inheritance works in Python. Suppose we have a base class named Animal that has a method named make_sound. Now we want to create specific classes for certain animals like cats and dogs that can produce their own sounds.

A Practical Example of Inheritance in Python

This section will demonstrate how to define classes using inheritance:

class Animal:
    def make_sound(self):
        print("Some sound")

class Dog(Animal):
    def make_sound(self):
        print("Bark")

class Cat(Animal):
    def make_sound(self):
        print("Meow")

Line by line explanation of the above code:

class Animal:
This line defines the base class Animal. This class has a method.

def make_sound(self):
This defines a method that produces a common sound. This method will later be overridden in the child classes.

print("Some sound")
The print statement prints out a common sound. You can replace this common sound in the child classes with specific animal sounds.

class Dog(Animal):
This defines the Dog class, which inherits from Animal.

def make_sound(self):
This overridden method make_sound in the Dog class produces the sound print("Bark"), which generates the dog's bark.

class Cat(Animal):
This defines the Cat class that also inherits from Animal.

def make_sound(self):
Similar to Dog, this method make_sound for the Cat class produces the sound of a cat, generating the meow.

FAQ

?

How do we define a subclass that inherits from a parent class?

?

Why do we need to override methods in subclasses?

?

Can we inherit from multiple parent classes?