What is Inheritance With Examples in Python

Inheritance is a key feature of object-oriented programming that allows a class to inherit attributes and methods from another class, referred to as the base or parent class. The class that inherits from the base class is called the derived or child class. In Python, inheritance is implemented using the class keyword and the concept of superclasses and subclasses.

Here’s an example that demonstrates inheritance in Python:

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

    def speak(self):
        print(f"{self.name} makes a sound.")


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

    def speak(self):
        print(f"{self.name} barks!")


# Create instances of the classes
animal = Animal("Generic Animal")
dog = Dog("Buddy", "Labrador")

# Call methods
animal.speak()
dog.speak()
Code language: Python (python)

In this example, we have a base class Animal that represents a generic animal. It has an __init__ method to initialize the name attribute and a speak method that prints a generic sound.

The derived class Dog inherits from the Animal class using the class Dog(Animal) syntax. It also has its own __init__ method that adds the breed attribute to the class. The speak method in the Dog class overrides the speak method in the base Animal class to provide a specific implementation for dogs.

When we create an instance of the Animal class and call the speak method, it will print a generic sound. However, when we create an instance of the Dog class and call the speak method, it will print “Buddy barks!” because the method has been overridden in the derived class.

Inheritance allows us to reuse code and create relationships between classes. The derived class inherits all the attributes and methods of the base class, and it can add its own attributes, methods, or override the existing ones to provide specialized behavior.

Real-time example for inheritance in Python

A real-time example of inheritance in Python can be seen in a scenario involving a car dealership. Let’s consider a simplified implementation:

class Vehicle:
    def __init__(self, brand, model, color):
        self.brand = brand
        self.model = model
        self.color = color
    
    def display_info(self):
        print(f"Brand: {self.brand}\nModel: {self.model}\nColor: {self.color}")


class Car(Vehicle):
    def __init__(self, brand, model, color, num_doors):
        super().__init__(brand, model, color)
        self.num_doors = num_doors
    
    def display_info(self):
        super().display_info()
        print(f"Number of doors: {self.num_doors}")


class ElectricCar(Car):
    def __init__(self, brand, model, color, num_doors, battery_capacity):
        super().__init__(brand, model, color, num_doors)
        self.battery_capacity = battery_capacity
    
    def display_info(self):
        super().display_info()
        print(f"Battery Capacity: {self.battery_capacity} kWh")


# Create instances of the classes
vehicle = Vehicle("Unknown", "Unknown", "Unknown")
car = Car("Ford", "Mustang", "Red", 2)
electric_car = ElectricCar("Tesla", "Model S", "Black", 4, 75)

# Display information
print("Vehicle Information:")
vehicle.display_info()
print("\nCar Information:")
car.display_info()
print("\nElectric Car Information:")
electric_car.display_info()
Code language: Python (python)

In this example, we have a base class Vehicle that represents a generic vehicle. It has attributes like brand, model, and color. The Vehicle class also has a method called display_info() that prints out the information about the vehicle.

The Car class inherits from the Vehicle class, adding an additional attribute num_doors. It overrides the display_info() method to include the number of doors in addition to the base vehicle information.

Finally, the ElectricCar class inherits from Car and adds another attribute battery_capacity. It also overrides the display_info() method to include the battery capacity in addition to the car information.

By utilizing inheritance, we can create specialized classes that inherit attributes and behaviors from their parent classes, while also having the ability to add their own unique attributes and behaviors. In this example, ElectricCar is a specialized type of Car which is, in turn, a specialized type of Vehicle.

What are the 5 types of inheritance in Python?


In Python, there are five types of inheritance:

Single inheritance:

In single inheritance, a class inherits from a single base class. This is the most common type of inheritance. For example:

class BaseClass:
    # Base class code

class DerivedClass(BaseClass):
    # Derived class code
Code language: Python (python)

Multiple inheritance:

Multiple inheritance allows a class to inherit from multiple base classes. In this case, the derived class inherits attributes and methods from all the base classes. For example:

class BaseClass1:
    # Base class 1 code

class BaseClass2:
    # Base class 2 code

class DerivedClass(BaseClass1, BaseClass2):
    # Derived class code
Code language: Python (python)

Multilevel inheritance:

Multilevel inheritance involves a chain of inheritance, where a derived class inherits from another derived class. In other words, a class can act as both a derived class and a base class at the same time. For example:

class BaseClass:
    # Base class code

class DerivedClass1(BaseClass):
    # Derived class 1 code

class DerivedClass2(DerivedClass1):
    # Derived class 2 code
Code language: Python (python)

Hierarchical inheritance:

Hierarchical inheritance occurs when multiple derived classes inherit from a single base class. Each derived class can have its own unique attributes and methods while sharing common attributes and methods from the base class. For example:

class BaseClass:
    # Base class code

class DerivedClass1(BaseClass):
    # Derived class 1 code

class DerivedClass2(BaseClass):
    # Derived class 2 code
Code language: Python (python)

Hybrid inheritance:

Hybrid inheritance combines multiple types of inheritance. It can be a combination of any of the above inheritance types.

Check our detailed guide: What is Hybrid Inheritance With Example in Python

For example:

class BaseClass1:
    # Base class 1 code

class BaseClass2:
    # Base class 2 code

class DerivedClass1(BaseClass1):
    # Derived class 1 code

class DerivedClass2(BaseClass1, BaseClass2):
    # Derived class 2 code
Code language: Python (python)

These different types of inheritance provide flexibility in organizing and reusing code in object-oriented programming, allowing for code modularity and creating relationships between classes.

Read More;

  • Dmytro Iliushko

    I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

    View all posts

Leave a Comment