Polymorphism in Python

Mannan Ul Haq
0

Polymorphism means having many forms. It's a fundamental concept in object-oriented programming (OOP) that permits objects of different types to be treated as if they are objects of a shared type. This allows for greater flexibility and extensibility in your code. In Python, due to its dynamic nature, polymorphism is intrinsically implemented.


Here's a brief overview of how polymorphism manifests in Python:


1. Duck Typing (Dynamic Polymorphism):

  • The term "duck typing" comes from the saying, "If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck." Python uses duck typing, which means that it determines the type of an object at runtime (not in advance during compilation because Python is interpreted).
  • The behavior or property of the object is more significant than its actual type. This means that if two different objects can be indexed (like a list and a string), they can be treated in the same way in this context, regardless of their actual data types.


Example:


def add(a, b):
    return a + b

print(add(10, 20))      # 30 (Integers)
print(add("Hello", " World"))  # Hello World (Strings)


In this example, the `add` function works for both numbers and strings. The appropriate operation is chosen at runtime based on the type of the arguments.


2. Polymorphism with Inheritance:

Python supports polymorphism through inheritance where derived classes can provide specific implementations of methods from their base class (Function Overriding).


Example:


class Animal:
    def make_sound(self):
        return "Some sound"

class Dog(Animal):
    def make_sound(self):
        return "Bark"

class Cat(Animal):
    def make_sound(self):
        return "Meow"

def animal_sound(animal):
    return animal.make_sound()

dog = Dog()
cat = Cat()

print(animal_sound(dog))  # Output: Bark
print(animal_sound(cat))  # Output: Meow


Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !