Concept of polymorphism in python (method overloading and overriding)
Here you will learn the concept of polymorphism in python using method overloading and overriding.
Polymorphism in Python is a fundamental concept that allows objects to be treated as an instances of their parent class rather than their actual class. This means that the same operation can behave differently on different classes. Polymorphism is commonly implemented through method overloading and method overriding.
Method Overloading
Method overloading refers to the ability to define multiple methods with the same name but different signatures (number or type of parameters). Python does not support method overloading directly as some other languages do (like Java or C++), but you can achieve similar behavior using default arguments or by manually handling arguments within a single method.
Example using default arguments:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Polymorphism: def display(self, a=None, b=None): if a is not None and b is not None: print(f"a: {a}, b: {b}") elif a is not None: print(f"a: {a}") else: print("No arguments given") ex = Polymorphism() ex.display() # No arguments given ex.display(5) # a: 15 ex.display(5, 10) # a: 15, b: 20 |
Output
No arguments given
a: 15
a: 15, b: 20
Example using variable-length arguments:
1 2 3 4 5 6 7 8 9 10 11 12 | class Poly: def display(self, *args): if len(args) == 1: print(f"a: {args[0]}") elif len(args) == 2: print(f"a: {args[0]}, b: {args[1]}") else: print("Invalid number of arguments") ex = Poly() ex.display(5) # a: 5 ex.display(10, 20) # a: 10, b: 20 |
Output
a: 5
a: 10, b: 20
Method Overriding
Method overriding allows a subclass to provide a specific implementation of a method that is predefined in its superclass. The overridden method in the subclass should have the same name and signature as the method in the parent class.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class Animal: def sound(self): return "Some sound" class Dog(Animal): def sound(self): return "Bark" class Cat(Animal): def sound(self): return "Meow" def make_sound(animal): print(animal.sound()) dog = Dog() cat = Cat() make_sound(dog) # Bark make_sound(cat) # Meow |
Output
Bark
Meow
In the above example, the Dog and Cat classes override the sound method of the Animal class. When we call make_sound method with Dog or Cat object, Here polymorphism is demonstrated by executing the appropriate overridden method.
Check out our other Python programming examples