Python Single Inheritance


Single Inheritance in Python

Single inheritance is a fundamental concept in object-oriented programming (OOP) where a class (called the child class or subclass) inherits attributes and methods from only one parent class (called the base class or superclass). This model promotes code reuse and establishes a hierarchical relationship between classes.

Key Features of Single Inheritance

  1. Single Parent Class: A child class can only inherit from one parent class, which helps avoid complexity and ambiguity that might arise from multiple inheritance.

  2. Code Reusability: Child classes can reuse the methods and attributes defined in the parent class, reducing code duplication.

  3. Method Overriding: Child classes can override methods from the parent class, providing specific implementations while still retaining access to the parent's functionality.

  4. Extensibility: Single inheritance allows for the extension of the parent class's functionality by adding new methods or attributes in the child class.

Example of Single Inheritance

Here’s an example to illustrate single inheritance in Python:

# Parent class class Animal: def __init__(self, name): self.name = name def speak(self): return f"{self.name} makes a sound." # Child class inheriting from Animal class Dog(Animal): def speak(self): # Overriding the parent method return f"{self.name} says Woof!" # Creating an instance of Dog my_dog = Dog("Buddy") # Accessing methods print(my_dog.speak()) # Output: Buddy says Woof! # Accessing the parent class's method print(my_dog.speak()) # Output: Buddy says Woof!

Explanation of the Example

  1. Parent Class (Animal):

    • The Animal class has an __init__ method that initializes the name attribute and a method speak() that returns a generic sound message.
  2. Child Class (Dog):

    • The Dog class inherits from the Animal class, meaning it has access to its attributes and methods.
    • The speak() method in the Dog class overrides the parent class's speak() method to provide a specific implementation for dogs, returning a sound that a dog makes.
  3. Creating an Instance: An instance of the Dog class is created with the name "Buddy".

  4. Method Access: The speak() method of the Dog class is called, which returns "Buddy says Woof!", demonstrating how the child class can provide its own implementation while still being related to the parent class.

Summary

  • Single inheritance involves a class inheriting from only one parent class, establishing a straightforward relationship.
  • It promotes code reuse, allowing child classes to access and build upon the functionality provided by the parent class.
  • Method overriding enables child classes to customize or extend the behavior of inherited methods.

If you have any further questions or need more examples, feel free to ask!