Python Polymorphism Tutorial
Polymorphism is an object-oriented programming (OOP) concept where the same function or method can have different behaviors depending on the object using it.
1. Polymorphism with Functions
A single function can operate on different data types.
Example: Using a Common Function for Different Data Types
def add(a, b):
return a + b
print(add(5, 10)) # Output: 15 (Integer Addition)
print(add("Hello ", "World")) # Output: Hello World (String Concatenation)
✅ Same function add()
behaves differently based on input types.
2. Polymorphism with Class Methods
Different classes can have methods with the same name, but different behavior.
Example: Different Classes with the Same Method Name
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Function using polymorphism
def animal_sound(animal):
print(animal.speak())
dog = Dog()
cat = Cat()
animal_sound(dog) # Output: Woof!
animal_sound(cat) # Output: Meow!
✅ The speak()
method behaves differently for each class.
3. Polymorphism with Inheritance (Method Overriding)
A child class can override a method of its parent class.
Example: Method Overriding
class Bird:
def fly(self):
return "Birds can fly"
class Penguin(Bird):
def fly(self):
return "Penguins cannot fly"
bird = Bird()
penguin = Penguin()
print(bird.fly()) # Output: Birds can fly
print(penguin.fly()) # Output: Penguins cannot fly
✅ The fly()
method is overridden in the Penguin
class.
4. Polymorphism with Abstract Classes (Using ABC
Module)
Abstract classes force subclasses to implement certain methods, enabling polymorphism.
Example: Using an Abstract Class
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog()
cat = Cat()
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
✅ Abstract methods ensure all subclasses define their own speak()
method.
5. Operator Overloading (Method Overloading in Python)
Python allows overloading operators like +
, -
, *
, etc., using special methods (dunder methods).
Example: Overloading the +
Operator
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
p1 = Point(2, 3)
p2 = Point(4, 5)
result = p1 + p2 # Calls __add__()
print(result.x, result.y) # Output: 6 8
✅ The +
operator is customized for Point
objects.
Conclusion
Polymorphism makes code more flexible and reusable by allowing different classes to have methods with the same name but different behavior.
0 comments:
Post a Comment