Python : Inheritance

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create a new class (subclass) based on an existing class (superclass). The subclass inherits attributes and methods from the superclass and can also have its own additional attributes and methods. This promotes code reuse and helps organize code into a hierarchical structure. Here's how inheritance works in Python:

Defining a Superclass (Base Class):


You define a superclass using the class keyword. The superclass contains attributes and methods that you want to share with subclasses.


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

    def make_sound(self):
        pass  # Placeholder method, to be overridden by subclasses

Creating Subclasses:


To create a subclass, you define a new class and specify the superclass in parentheses after the class name.


class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

 

Accessing Superclass Methods:


Subclasses inherit methods from the superclass and can override them with their own implementations. You can access superclass methods using the super() function.


class Dog(Animal):
    def make_sound(self):
        return super().make_sound() + " Woof!"

 

Calling Superclass Constructor:


Subclasses can call the constructor of the superclass using super().__init__() to initialize inherited attributes.


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

 

Method Resolution Order (MRO):


Python uses the C3 linearization algorithm to determine the method resolution order for classes with multiple inheritance. You can access the MRO using the __mro__ attribute.


print(Dog.__mro__)  # Output: (<class '__main__.Dog'>, <class '__main__.Animal'>, <class 'object'>)
 

Multiple Inheritance:


Python supports multiple inheritance, allowing a subclass to inherit from multiple superclasses.


class A:
    def method_a(self):
        print("Method A")

class B:
    def method_b(self):
        print("Method B")

class C(A, B):
    pass

obj = C()
obj.method_a()  # Output: Method A
obj.method_b()  # Output: Method B

Method Overriding:


Subclasses can override methods inherited from the superclass with their own implementations.


class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

dog = Dog()
dog.speak()  # Output: Dog barks

 

Inheritance is a powerful mechanism in Python that allows you to create hierarchical relationships between classes and promote code reuse. It helps you build more maintainable and organized code by organizing related classes into a hierarchical structure.