Single inheritance

Single inheritance refers to the scenario where a class (child or derived class) inherits from one and only one base class (parent class). This forms a simple, straightforward hierarchy.

Key Concepts of Single Inheritance

  1. Base Class (Parent Class): The class whose properties and methods are inherited by another class.
  2. Derived Class (Child Class): The class that inherits the properties and methods of the base class.

Why Use Single Inheritance?

Single inheritance helps to:

  • Reusability: Reuse code across multiple classes.
  • Maintainability: Make code easier to maintain by organizing functionality into base and derived classes.
  • Extensibility: Extend the functionality of existing code without modifying it.

Example of Single Inheritance in Python

Let’s look at a practical example to understand single inheritance better.

Step 1: Define the Base Class

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("Subclass must implement abstract method")
    
    def move(self):
        print(f"{self.name} is moving")

Step 2: Define the Derived Class

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

Step 3: Instantiate and Use the Derived Class

if __name__ == "__main__":
    my_dog = Dog("Buddy")
    print(my_dog.speak())  # Output: Buddy says Woof!
    my_dog.move()          # Output: Buddy is moving

Detailed Breakdown

  1. Base Class Animal:
    • Initialization: The __init__ method initializes the name attribute.
    • speak Method: Defined as an abstract method to be implemented by any derived class.
    • move Method: Prints a simple message indicating the animal is moving.
  2. Derived Class Dog:
    • Inherits the name attribute and move method from the Animal class.
    • Implements the speak method, providing the functionality specific to Dog.