Polymorphism is one of the core 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 super class. This is achieved by having methods in different classes with the same name, but potentially different implementations.
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its super class.
Example:
class Animal:
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
# Creating instances of Dog and Cat
dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
Duck typing is a concept related to dynamic typing where an object's methods and properties determine the valid semantics, rather than the object's inheritance from a particular class.
Example:
class Bird:
def fly(self):
return "Flying high"
class Airplane:
def fly(self):
return "Flying with jet engines"
# Polymorphic function
def let_it_fly(obj):
return obj.fly()
# Using duck typing
bird = Bird()
airplane = Airplane()
print(let_it_fly(bird)) # Output: Flying high
print(let_it_fly(airplane)) # Output: Flying with jet engines
Polymorphism can also be used with functions and classes to perform a single action in different ways.
Example:
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement abstract method")
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
# Polymorphic function
def print_area(shape):
print(f"The area is: {shape.area()}")
# Using polymorphism
square = Square(4)
circle = Circle(3)
print_area(square) # Output: The area is: 16
print_area(circle) # Output: The area is: 28.26
In this example, the print_area function can handle different types of Shape objects, each providing its own implementation of the area method.