Inheritance and Polymorphism in Python

Inheritance and polymorphism are two fundamental concepts in object-oriented programming (OOP). Python, being an object-oriented language, fully supports both concepts.

Inheritance:

Inheritance is the mechanism by which a class can derive properties and behaviors from another class. The class from which properties and behaviors are inherited is called the base class or superclass, and the class that inherits from the base class is called the derived class or subclass.

Here's an example:

pythonCopy codeclass Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):  # Dog inherits from Animal
    def bark(self):
        print("Dog barks")

dog = Dog()
dog.bark()   # Output: Dog barks
dog.speak()  # Output: Animal speaks

In this example, the Dog class inherits from the Animal class. The Dog class can access the speak() method defined in the Animal class.

Polymorphism:

Polymorphism is the ability of different types of objects to be treated as if they are instances of a common superclass. In Python, polymorphism is achieved through method overriding and method overloading.

Method overriding occurs when a subclass provides a specific implementation of a method that is already provided by its superclass. When the method is called on an object of the subclass, the overridden method is executed.

pythonCopy codeclass Animal:
    def speak(self):
        print("Animal speaks")

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

animal = Animal()
dog = Dog()

animal.speak()  # Output: Animal speaks
dog.speak()     # Output: Dog barks

In this example, both Animal and Dog classes have a speak() method. When speak() is called on an instance of Dog, the overridden method in Dog is executed.

Method overloading, on the other hand, is not directly supported in Python as it is in some other languages. Python does not support multiple methods with the same name differing only in the number or type of their parameters. However, you can achieve a form of overloading using default parameters or variable-length arguments.

These concepts of inheritance and polymorphism are key to building modular, extensible, and reusable code in Python, especially in large projects. Check out these free resources for more insights like this:

Online Python Tutorial

Online Python Compiler

Data Science Course