Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Polymorphism → Polymorphism

Polymorphism

Polymorphism

Polymorphism in Python

Polymorphism, a core concept in Object-Oriented Programming (OOP), translates to "many forms." It allows objects of different classes to be treated as objects of a common type. This means a single interface (like a function call) can be used to represent different functionalities depending on the object's type. Python achieves polymorphism through several mechanisms:

1. Duck Typing

Python's dynamic typing system facilitates polymorphism implicitly. It doesn't enforce strict type checking; instead, it relies on "duck typing": "If it walks like a duck and quacks like a duck, then it must be a duck." If an object possesses the necessary methods, it can be used regardless of its class.
Duck Typing in polymorphism example class Dog: def speak(self): print("Woof!") class Cat: def speak(self): print("Meow!") class Duck: def speak(self): print("Quack!") def animal_sound(animal): animal.speak() # No explicit type checking dog = Dog() cat = Cat() duck = Duck() animal_sound(dog) animal_sound(cat) animal_sound(duck)

Output

Woof! Meow! Quack!
Here, `animal_sound` works with `Dog`, `Cat`, and `Duck` objects even though they are different classes. The key is that all three classes have a `speak` method.

2. Method Overriding (Runtime Polymorphism)

Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. At runtime, the appropriate method (from the subclass) is called, demonstrating polymorphism.
Method Overriding (Runtime Polymorphism) example class Animal: def speak(self): print("Generic animal sound") class Dog(Animal): def speak(self): print("Woof!") class Cat(Animal): def speak(self): print("Meow!") dog = Dog() cat = Cat() animal = Animal() dog.speak() cat.speak() animal.speak()

Output

Woof! Meow! Generic animal sound
The `speak` method is overridden in both `Dog` and `Cat`. When called, the version specific to the object's class is executed.

3. Operator Overloading

Python allows you to define how standard operators (+, -, *, /, etc.) behave when used with objects of your custom classes. This is a form of polymorphism because the same operator performs different actions based on the operand types.
Operator Overloading class Point: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): # Overloading the + operator return Point(self.x + other.x, self.y + other.y) def __str__(self): # Overloading the str() function for better representation return f"({self.x}, {self.y})" p1 = Point(1, 2) p2 = Point(3, 4) p3 = p1 + p2 # Using + operator with Point objects print(p3)

Output

(4, 6)
Here, the `+` operator is overloaded to add the coordinates of two `Point` objects.

4. Polymorphism with Abstract Base Classes (ABCs)

ABCs (from the `abc` module) provide a way to define a common interface for a set of subclasses. Subclasses are then *required* to implement specific methods. This enforces a consistent structure and enables strong polymorphism.
Polymorphism with Abstract Base Classes (ABCs) from abc import ABC, abstractmethod class Shape(ABC): # Abstract Base Class @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 circle = Circle(5) square = Square(4) print(circle.area()) print(square.area()) #This will raise an error because Shape is abstract and cannot be instantiated #shape = Shape()

Output

78.53975 16
In summary, Python's polymorphism, driven by duck typing and complemented by method overriding, operator overloading, and ABCs, provides flexibility and extensibility, making it easy to write adaptable and maintainable code. The key is that the same method name or operator can have different behaviors depending on the context (the object's type).

Tutorials