Python OOPs


Python SQLite


Examples


Others


Polymorphism in Python


  • Polymorphism is a concept of object-oriented programming that allows objects of different classes to be treated as objects of a common superclass
  • It enables methods in different classes to be called through the same interface, enhancing flexibility and reusability.

Types of Polymorphism

1. Method Overriding (Inheritance-Based Polymorphism)

Method overriding a subclass provides a specific implementation of a method that is already defined in its superclass.Its dynamic nature allows to runtime polymorphism,the code enabled the adaptable and flexible also.

Example
class Birds:
    def speak(self):
        return "Birds speaks"

class Parrots(Birds):
    def speak(self):
        return "Talk"

class Ducks(Birds):
    def speak(self):
        return "Quack"

# Using polymorphism
Birdss = [Parrots(), Ducks(), Birds()]

for Birds in Birdss:
    print(Birds.speak())

Output

Talk
Quack
Birds speaks  
2. Duck Typing (Dynamic Polymorphism)

Python’s dynamic typing allows polymorphism without explicit inheritance. As long as the object implements the required method, it works.

Example
class Bird:
    def fly(self):
        return "Flap flap!"

class Plane:
    def fly(self):
        return "Zoom zoom!"

# A function using polymorphism
def perform_fly_action(obj):
    print(obj.fly())

bird = Bird()
plane = Plane()

perform_fly_action(bird) 
perform_fly_action(plane)

Output

Flap flap!
Zoom zoom!
3. Built-in Functions

Built-in functions like len, sorted, and map exhibit polymorphism as they can operate on objects of different types as long as those objects support the expected interface.

Example
print(len("Hello World!"))      # Works on strings
print(len([1, 2, 3]))    # Works on lists
print(len({"a": 1, "b": 2}))  # Works on dictionaries

Output

12   #string length
3    #list length
2    #dict length
4. Operator Overloading

Polymorphism can be implemented by overloading operators for user-defined classes. This is done using special methods like __add__, __sub__, etc.

Example
class loading:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return loading(self.x + other.x, self.y + other.y)

    def __str__(self):
        return f"loading({self.x}, {self.y})"

a1 = loading(7, 8)
a2 = loading(3, 4)

print(a1 + a2) 

Output

loading(10, 12)