Explaining Inheritance and Polymorphism in Python - Omnath Dubey

Inheritance and polymorphism are fundamental concepts in object-oriented programming (OOP) that enable code reuse, extensibility, and flexibility. In Python, these concepts are implemented using class inheritance and method overriding. Let's explore how inheritance and polymorphism work in Python:

1. Inheritance:

Inheritance is the mechanism by which a new class (subclass) can inherit attributes and methods from an existing class (superclass). This promotes code reuse and allows the creation of specialized classes that extend the functionality of their parent classes.

Example:


class Animal:

    def speak(self):

        print("Animal speaks")


class Dog(Animal):  # Dog inherits from Animal

    def bark(self):

        print("Dog barks")


# Creating an instance of Dog

dog = Dog()

dog.speak()  # Inherits the speak() method from Animal class

dog.bark()   # Calls the bark() method specific to Dog class


2. Polymorphism:

Polymorphism refers to the ability of different classes to be treated as instances of a common superclass. This allows methods to be defined in the superclass and overridden in subclasses to provide specialized implementations. Polymorphism promotes flexibility and code extensibility.


Example:


class Animal:

    def speak(self):

        print("Animal speaks")


class Dog(Animal):

    def speak(self):  # Override the speak() method of Animal

        print("Dog barks")


class Cat(Animal):

    def speak(self):  # Override the speak() method of Animal

        print("Cat meows")


# Creating instances of Dog and Cat

dog = Dog()

cat = Cat()


# Polymorphic behavior

dog.speak()  # Calls the overridden speak() method in Dog class

cat.speak()  # Calls the overridden speak() method in Cat class


In the above examples, `Dog` and `Cat` are subclasses of `Animal`. They inherit the `speak()` method from the `Animal` class but provide their own implementations specific to each subclass. This demonstrates polymorphic behavior, where objects of different classes are treated interchangeably based on their common superclass.

In Python, polymorphism is achieved through dynamic method resolution (late binding), where the method implementation is determined at runtime based on the object's actual type. This allows for flexible and versatile code that can adapt to different object types without explicit type checking.