Python Runtime polymorphism

Share Your Love

Python Runtime polymorphism, also known as dynamic polymorphism or late binding, is a feature of object-oriented programming languages like Python. It allows different objects to respond to the same method call in different ways, based on their specific types or class hierarchy.

In Python, runtime polymorphism is achieved through method overriding, where a subclass provides its own implementation of a method that is already defined in its parent class. The specific implementation of the method that gets executed is determined at runtime, based on the actual type of the object.

Here’s an example to demonstrate runtime polymorphism in Python:

class Animal:
    def make_sound(self):
        print("Animal makes a sound")

class Dog(Animal):
    def make_sound(self):
        print("Dog barks")

class Cat(Animal):
    def make_sound(self):
        print("Cat meows")

# Create objects of different types
animal = Animal()
dog = Dog()
cat = Cat()

# Call the make_sound method on different objects
animal.make_sound()  # Output: Animal makes a sound
dog.make_sound()     # Output: Dog barks
cat.make_sound()     # Output: Cat meows

In the example above, the Animal class has a make_sound method that prints “Animal makes a sound”. The Dog class and Cat class are subclasses of Animal and override the make_sound method with their own implementations.

At runtime, when make_sound is called on different objects (animal, dog, cat), the appropriate implementation of the method is invoked based on the actual type of the object. This is determined dynamically, allowing each object to respond to the method call differently.

Runtime polymorphism allows for flexibility and extensibility in object-oriented programming. It enables different objects to exhibit different behaviors based on their specific types, providing a way to handle different objects uniformly through a common interface.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter