Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It is a way to perform a single action in different forms. Polymorphism is achieved through method overriding and interfaces in Python.
Key Concepts
-
Polymorphism:
- The ability of different objects to respond to the same method call in different ways.
- Allows for flexibility and integration of different types of objects.
-
Method Overriding:
- A subclass provides a specific implementation of a method that is already defined in its superclass.
- Enables a class to inherit methods from another class and modify them to fit its needs.
-
Duck Typing:
- A concept related to polymorphism where the type or class of an object is less important than the methods it defines.
- "If it looks like a duck and quacks like a duck, it must be a duck."
Practical Examples
Example 1: Method Overriding
class Animal:
def sound(self):
return "Some generic sound"
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
# Creating objects
dog = Dog()
cat = Cat()
# Demonstrating polymorphism
print(dog.sound()) # Output: Bark
print(cat.sound()) # Output: MeowExplanation:
- The
Animalclass has a methodsoundthat returns a generic sound. - The
DogandCatclasses override thesoundmethod to provide specific implementations. - When
soundis called on aDogobject, it returns "Bark", and when called on aCatobject, it returns "Meow".
Example 2: Duck Typing
class Bird:
def fly(self):
return "Flying high!"
class Airplane:
def fly(self):
return "Flying at 30,000 feet!"
def let_it_fly(flying_object):
print(flying_object.fly())
# Creating objects
bird = Bird()
airplane = Airplane()
# Demonstrating duck typing
let_it_fly(bird) # Output: Flying high!
let_it_fly(airplane) # Output: Flying at 30,000 feet!Explanation:
- Both
BirdandAirplaneclasses have aflymethod. - The
let_it_flyfunction accepts any object that has aflymethod, demonstrating duck typing. - The actual class of the object is not important; what matters is that the object has a
flymethod.
Exercises
Exercise 1: Method Overriding
Create a base class Shape with a method area that returns 0. Then, create two subclasses Rectangle and Circle that override the area method to return the area of the shape.
class Shape:
def area(self):
return 0
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)
# Test the classes
rectangle = Rectangle(5, 10)
circle = Circle(7)
print(rectangle.area()) # Output: 50
print(circle.area()) # Output: 153.93804002589985Exercise 2: Duck Typing
Create two classes Car and Boat, each with a method move. Then, write a function start_journey that accepts an object and calls its move method.
class Car:
def move(self):
return "Driving on the road!"
class Boat:
def move(self):
return "Sailing on the water!"
def start_journey(vehicle):
print(vehicle.move())
# Test the function
car = Car()
boat = Boat()
start_journey(car) # Output: Driving on the road!
start_journey(boat) # Output: Sailing on the water!Common Mistakes and Tips
-
Mistake: Forgetting to override a method in the subclass.
- Tip: Ensure that the method signature in the subclass matches the one in the superclass.
-
Mistake: Assuming that polymorphism only works with inheritance.
- Tip: Remember that duck typing allows polymorphism without inheritance.
-
Mistake: Not understanding the importance of method signatures.
- Tip: Ensure that overridden methods have the same name and parameters as the method in the superclass.
Conclusion
Polymorphism is a powerful feature in Python that allows for flexible and reusable code. By understanding and utilizing method overriding and duck typing, you can create programs that are both robust and adaptable. Practice the exercises provided to reinforce your understanding of polymorphism and its applications in Python.
Python Programming Course
Module 1: Introduction to Python
- Introduction to Python
- Setting Up the Development Environment
- Python Syntax and Basic Data Types
- Variables and Constants
- Basic Input and Output
Module 2: Control Structures
Module 3: Functions and Modules
- Defining Functions
- Function Arguments
- Lambda Functions
- Modules and Packages
- Standard Library Overview
Module 4: Data Structures
Module 5: Object-Oriented Programming
Module 6: File Handling
Module 7: Error Handling and Exceptions
Module 8: Advanced Topics
- Decorators
- Generators
- Context Managers
- Concurrency: Threads and Processes
- Asyncio for Asynchronous Programming
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with unittest
- Test-Driven Development
- Debugging Techniques
- Using pdb for Debugging
Module 10: Web Development with Python
- Introduction to Web Development
- Flask Framework Basics
- Building REST APIs with Flask
- Introduction to Django
- Building Web Applications with Django
Module 11: Data Science with Python
- Introduction to Data Science
- NumPy for Numerical Computing
- Pandas for Data Manipulation
- Matplotlib for Data Visualization
- Introduction to Machine Learning with scikit-learn
