Polymorphism

Polymorphism is a concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common base class. The term “polymorphism” means “many forms”, and it is used to describe the ability of a single function or method to operate on different types of data.

In Python, polymorphism is achieved through the use of inheritance and the ability of classes to override methods of their base classes. For example, a base class Animal might have a method called speak(), and different derived classes like Dogs, Cats, and Birds could override this method to provide their own implementation.

Here is an example of polymorphism in python:

class Animals:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def speak(self):
        pass

class Dogs(Animals):
    def __init__(self, name):
        super().__init__(name, species="Dog")

    def speak(self):
        print("Woof woof!")

class Cats(Animals):
    def __init__(self, name):
        super().__init__(name, species="Cat")

    def speak(self):
        print("Meow meow!")

class Birds(Animals):
    def __init__(self, name):
        super().__init__(name, species="Bird")

    def speak(self):
        print("Tweet tweet!")

animals = [Dogs("Max"), Cats("Molly"), Birds("Tweety")]

for animal in animals:
    animal.speak()

In this example, we have a base class Animals with a method called speak() which is implemented in the derived classes Dogs, Cats, and Birds differently, yet we can call the speak() method on all of these classes as they are all objects of the base class Animals and that’s the polymorphism.

In this example, the output would be:

Woof woof!
Meow meow!
Tweet tweet!

It’s worth mentioning that polymorphism is not limited to classes but it’s a general concept that applies to any type of object, function, or method that can operate on multiple types of data.

Polymorphism in Python should be used when:

  1. You want to write code that can work with objects of different classes. For example, if you have a function that takes an object as an argument and performs some action on it, you can use polymorphism to make sure that the function works with any object that has the appropriate methods or attributes, regardless of its class.
  2. You want to create a more flexible and maintainable code. Polymorphism allows you to write code that can work with objects of different classes without having to know their specific types, which makes it easier to update or modify the code without having to change the objects that use it.
  3. You want to improve the testability of the code. Polymorphism allows you to write test cases that can be used to test multiple classes at once, which makes it easier to test the code and identify any bugs.
  4. You want to design a program with a simpler and cleaner interface. Polymorphism allows different objects to be used interchangeably, so that the same method or function can work with objects of different classes without requiring explicit type checking.
  5. You want to implement a strategy pattern. Polymorphism allows you to define a common interface for different objects, and then use those objects interchangeably. This can help to make the code more flexible and maintainable, and also to write more testable code.

In general, polymorphism should be used whenever there’s a need to write code that can work with objects of different classes, or when there’s a need to design a program with a simpler and cleaner interface.

Difference between Inheritance and Polymorphism in Python:

InheritancePolymorphism
Inheritance is a mechanism that allows a new class to inherit properties and methods from an existing class.Polymorphism is a mechanism that allows objects of different classes to be treated as objects of a common superclass.
The subclasses inherit the properties and methods of the superclass.The objects of different classes can be used interchangeably.
Inheritance is mainly used for code reusability.Polymorphism is mainly used for flexibility and maintainability.
Inheritance can be implemented using the class keyword.Polymorphism can be implemented using method overriding, method overloading and duck typing.

Inheritance allows you to create a new class that is a modified version of an existing class. The new class is called the subclass, and the existing class is the superclass. Polymorphism allows objects of different classes to be treated as objects of a common superclass. This is useful in situations where you need to write code that can work with objects of different classes.