does python support polymorphism

Does Python Support Polymorphism?

Yes, Python supports polymorphism.

Polymorphism is a concept in object-oriented programming where objects of different classes can be treated as if they are of the same class. It allows us to write flexible, reusable code that can work with objects of different types.

How does Polymorphism work in Python?

In Python, polymorphism is achieved through method overriding and method overloading.

  • Method Overriding: When a method in a subclass has the same name and signature as a method in its superclass, the subclass method overrides the superclass method. This means that when an object of the subclass is used to call the overridden method, the subclass method is executed instead of the superclass method.
  • Method Overloading: Python does not support method overloading in the traditional sense (i.e. defining multiple methods with the same name but different parameters). However, we can achieve similar functionality using default arguments or variable-length argument lists.

Here's an example of method overriding:


    class Animal:
        def __init__(self, name):
            self.name = name
            
        def speak(self):
            raise NotImplementedError("Subclass must implement abstract method")
    
    class Dog(Animal):
        def speak(self):
            return "Woof!"
    
    class Cat(Animal):
        def speak(self):
            return "Meow!"
    
    dog = Dog("Rufus")
    cat = Cat("Mittens")
    
    print(dog.speak()) # Output: "Woof!"
    print(cat.speak()) # Output: "Meow!"
    

In this example, the Animal class has an abstract method called 'speak'. This means that any subclass of Animal must implement their own version of the 'speak' method. The Dog and Cat classes do just that, and their implementations override the 'speak' method of the Animal class.

When we call the 'speak' method on an instance of Dog or Cat, their respective implementations of the method are executed.

Here's an example of using default arguments to achieve method overloading:


    class Math:
        def add(self, x, y=0):
            return x + y
    
    m = Math()
    
    print(m.add(2, 3)) # Output: 5
    print(m.add(2)) # Output: 2
    

In this example, the 'add' method of the Math class takes two arguments, but the second argument has a default value of 0. This means that we can call 'add' with either one or two arguments.