Cover Image for Polymorphism in Python
168 views

Polymorphism in Python

Polymorphism is one of the four fundamental principles of object-oriented programming (OOP), along with encapsulation, inheritance, and abstraction. It allows objects of different classes to be treated as objects of a common superclass. In Python, polymorphism is supported through method overriding and duck typing.

Here’s a closer look at polymorphism in Python:


Method Overriding:
Polymorphism in Python is often achieved through method overriding, where a subclass provides a specific implementation of a method that is already defined in its superclass. The method in the subclass has the same name and parameters as the method in the superclass.

Python
 class Animal:
     def speak(self):
         pass

 class Dog(Animal):
     def speak(self):
         return "Woof!"

 class Cat(Animal):
     def speak(self):
         return "Meow!"

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

 dog = Dog()
 cat = Cat()

 print(animal_sound(dog))  # Outputs: "Woof!"
 print(animal_sound(cat))  # Outputs: "Meow!"

In this example, both Dog and Cat are subclasses of Animal and override the speak method with their specific implementations. When the animal_sound function is called with different objects, it invokes the appropriate speak method based on the object’s actual class.


Duck Typing:
Python follows a principle called “duck typing,” which means that the type or class of an object is determined by its behavior (methods and properties) rather than its explicit type. In other words, if an object behaves like a certain type, it is treated as that type.

Python
 class Bird:
     def speak(self):
         pass

 class Duck(Bird):
     def speak(self):
         return "Quack!"

 class Crow(Bird):
     def speak(self):
         return "Caw!"

 def bird_sound(bird):
     return bird.speak()

 duck = Duck()
 crow = Crow()

 print(bird_sound(duck))  # Outputs: "Quack!"
 print(bird_sound(crow))  # Outputs: "Caw!"

This example, the bird_sound function takes any object that has a speak method and invokes it. This demonstrates duck typing, where objects are treated based on their behavior, not their specific class.

Polymorphism in Python is powerful because it allows you to write more flexible and reusable code. It enables you to work with objects of different classes in a consistent way, making your code more adaptable and extensible.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS