Polymorphism is a core concept in Object-Oriented Programming (OOP) that allows methods and functions to take on many forms. In Python, polymorphism enables objects of different classes to be treated as objects of a common superclass. The most common use of polymorphism is in method overriding, where a subclass can provide a specific implementation of a method that is already defined in its superclass.
In the following example, we demonstrate method overriding where different classes implement a method with the same name but different behaviors.
class Animal:
def speak(self): # Method in the parent class
return "Animal speaks"
class Dog(Animal):
def speak(self): # Overriding the speak method
return "Woof!"
class Cat(Animal):
def speak(self): # Overriding the speak method
return "Meow!"
# Function to demonstrate polymorphism
def animal_sound(animal):
print(animal.speak())
# Creating instances of Dog and Cat
dog = Dog()
cat = Cat()
# Calling the same function with different objects
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!
In this example, the animal_sound
function can accept any object of type Animal
(or its subclasses) and calls the speak
method, demonstrating polymorphism.
Duck typing in Python allows you to use polymorphism based on whether an object can perform the required behavior rather than its actual type.
class Bird:
def fly(self):
return "Flapping wings!"
class Airplane:
def fly(self):
return "Taking off!"
# Function demonstrating duck typing
def let_it_fly(flying_object):
print(flying_object.fly())
# Creating instances of Bird and Airplane
sparrow = Bird()
boeing = Airplane()
# Calling the function with different objects
let_it_fly(sparrow) # Output: Flapping wings!
let_it_fly(boeing) # Output: Taking off!
In this case, both Bird
and Airplane
have a method called fly
, and the let_it_fly
function can accept any object that implements a fly
method, regardless of its actual type.
Polymorphism is essential in Python as it allows for writing more generic and reusable code, making it easier to manage and extend complex systems!
@aCodeTutorials All Rights Reserved
privacy policy | about