Python Polymorphism
Polymorphism means having many forms. In Python, polymorphism allows us to define methods in the child class that have the same name as the methods in the parent class. This allows for different implementations.
Example 1: Polymorphism with Classes
Create two classes with the same method names but different implementations.
# Polymorphism with classes
class India:
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the primary language of India.")
class Russia:
def capital(self):
print("Moscow is the capital of Russia.")
def language(self):
print("Russian is the primary language of Russia.")
country = India()
country.capital()
country.language()
country = Russia()
country.capital()
country.language()
New Delhi is the capital of India.
Hindi is the primary language of India.
Moscow is the capital of Russia.
Russian is the primary language of Russia.
Example 2: Polymorphism with Inheritance
Use method overriding to achieve polymorphism.
# Polymorphism with inheritance
class Bird:
def fly(self):
print("Some birds can fly.")
class Parrot(Bird):
def fly(self):
print("Parrots can fly.")
class Penguin(Bird):
def fly(self):
print("Penguins cannot fly.")
bird = Bird()
bird.fly()
parrot = Parrot()
parrot.fly()
penguin = Penguin()
penguin.fly()
Some birds can fly.
Parrots can fly.
Penguins cannot fly.
Example 3: Polymorphism with Functions
Create a function that can take any object and call its methods.
# Polymorphism with functions
def describe_animal(animal):
animal.sound()
class Dog:
def sound(self):
print("Woof")
class Cat:
def sound(self):
print("Meow")
dog = Dog()
cat = Cat()
describe_animal(dog)
describe_animal(cat)
Woof
Meow
Example 4: Polymorphism with Abstract Classes
Use the abc
module to create abstract base classes.
# Polymorphism with abstract classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
import math
return math.pi * self.radius ** 2
shapes = [Rectangle(3, 4), Circle(5)]
for shape in shapes:
print("Area:", shape.area())
Area: 12
Area: 78.53981633974483
Example 5: Polymorphism with Built-in Functions
Use the len()
function with different object types.
# Polymorphism with len()
print(len("Tamil")) # String
print(len([1, 2, 3, 4])) # List
print(len({'a': 1, 'b': 2})) # Dictionary
5
4
2
Example 6: Operator Overloading
Define methods to overload operators in a class.
# Operator overloading
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3)
Vector(6, 8)
Explanation: Polymorphism allows for flexibility and integration of objects with similar interfaces. It is achieved through method overriding, duck typing, and operator overloading.