Python tutorials > Object-Oriented Programming (OOP) > Polymorphism > Examples of polymorphism?
Examples of polymorphism?
What is Polymorphism?
Duck Typing (Implicit Polymorphism)
Duck and Person classes have a quack() method. The make_it_quack() function doesn't care about the object's type; it only cares that the object has a quack() method.
class Duck:
def quack(self):
return "Quack!"
class Person:
def quack(self):
return "I'm imitating a duck: Quack!"
def make_it_quack(animal):
print(animal.quack())
duck = Duck()
person = Person()
make_it_quack(duck)
make_it_quack(person)
Explanation of Duck Typing
Polymorphism with Inheritance
Animal class defines a speak() method. The Dog and Cat classes inherit from Animal and override the speak() method to provide their own implementations. The animal_sound() function can accept any object that is an instance of Animal (or a subclass of Animal) and call its speak() method. This is a classic example of polymorphism using inheritance.
class Animal:
def speak(self):
return "Generic animal sound"
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_sound(animal):
print(animal.speak())
animal = Animal()
dog = Dog()
cat = Cat()
animal_sound(animal)
animal_sound(dog)
animal_sound(cat)
Explanation of Inheritance Polymorphism
speak() method) but provide their specific implementations. This allows treating different types of objects uniformly through a common interface. The animal_sound function doesn't need to know the specific type of animal; it only knows that it can call the speak() method.
Polymorphism with Abstract Base Classes (ABCs)
Shape class is an abstract base class with an abstract method area(). The Circle and Square classes inherit from Shape and implement the area() method. Attempting to instantiate `Shape` will raise a `TypeError`. ABCs enforce a certain interface across different classes.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
def print_area(shape):
print(f"Area: {shape.area()}")
circle = Circle(5)
square = Square(4)
print_area(circle)
print_area(square)
Explanation of Abstract Base Classes
Real-Life Use Case: File Handling
read()) remains the same. Polymorphism allows you to handle various file types through a common interface. The process_file() function can handle both TextFile and CSVFile objects because they both have a read() method, even though the implementation is different.
class TextFile:
def __init__(self, filename):
self.filename = filename
def read(self):
with open(self.filename, 'r') as f:
return f.read()
class CSVFile:
def __init__(self, filename):
self.filename = filename
def read(self):
import csv
with open(self.filename, 'r') as f:
reader = csv.reader(f)
return list(reader)
def process_file(file):
data = file.read()
print(data)
text_file = TextFile('my_text_file.txt')
csv_file = CSVFile('my_csv_file.csv')
process_file(text_file)
process_file(csv_file)
Best Practices
Interview Tip
When to use Polymorphism
Pros
Cons
FAQ
-
What is the difference between duck typing and inheritance polymorphism?
Duck typing relies on the presence of specific methods regardless of inheritance, while inheritance polymorphism relies on inheriting from a common base class and overriding methods. Duck typing is implicit, while inheritance polymorphism is explicit. -
When should I use Abstract Base Classes (ABCs)?
Use ABCs when you want to enforce that subclasses implement specific methods. This provides a clear contract between the base class and its subclasses. -
Is method overloading supported in Python in the traditional sense?
No, Python does not support method overloading in the same way as languages like Java or C++. However, you can achieve similar results using default argument values or variable-length argument lists.