Python Inheritance

In Python, inheritance is an essential part of Object-Oriented Programming (OOP). It lets a class, known as a child or subclass, inherit attributes and methods from another class, called a parent or superclass. This builds on existing code, promotes code reuse, and creates a clear class structure.

Benefits of Inheritance

Code Reusability: You can reuse existing code without rewriting it.

Hierarchical Class Structure: It creates a clear class hierarchy and logical structure.

Modularity and Extensibility: You can easily extend the functionality of existing classes.

Basic Inheritance

Inheritance allows the subclass to use the properties and methods of the superclass. The subclass can also override methods and add new attributes or methods.

Example:


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

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

# Child class
class Dog(Animal):
    def speak(self):
        return f"{self.name} barks"

# Creating an instance of Dog
my_dog = Dog("Tommy")
print(my_dog.speak())  # Output: Tommy barks

In this example:

Animal is the parent class, with a method speak.

Dog is a child class that inherits from Animal and overrides the speak method.

Types of Inheritance

Single Inheritance

A child class inherits from only one parent class.


class Parent:
    pass

class Child(Parent):
    pass

Multiple Inheritance

A child class inherits from more than one parent class.


class Parent1:
    pass

class Parent2:
    pass

class Child(Parent1, Parent2):
    pass

Multilevel Inheritance

A chain of inheritance occurs when a class is derived from another derived class.


class Grandparent:
    pass

class Parent(Grandparent):
    pass

class Child(Parent):
    pass

Using super() to Access the Parent Class

The super() function allows a subclass to call a method or constructor from its parent class. This is helpful when you override methods in the subclass but still want to use the parent’s features.


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

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

class Cat(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Call the parent constructor
        self.breed = breed

    def speak(self):
        return f"{self.name} meows"

# Creating an instance of Cat
my_cat = Cat("Whiskers", "Siamese")
print(my_cat.speak())         # Output: Whiskers meows
print(my_cat.breed)           # Output: Siamese

Method Overriding

In a child class, you can override a method from the parent class by defining it with the same name. This helps customize the inherited behavior.


class Animal:
    def speak(self):
        return "Some generic sound"

class Dog(Animal):
    def speak(self):
        return "Bark"

my_dog = Dog()
print(my_dog.speak())  # Output: Bark