How is polymorphism achieved in Python?
Achieving polymorphism in Python
Polymorphism in Python is achieved through method overriding and overloading. Python does not have traditional method overloading, but it makes extensive use of method overriding.
Polymorphism allows objects of different classes to be treated as objects of a common super class. This is often achieved through inheritance and method overriding. Here's how it works in Python:
Method Overriding: When a subclass provides a specific implementation of a method that is already defined in its superclass, it's called method overriding. It allows objects of different classes to be treated uniformly if they share the same method name.
Example:
Code:
class Animal:
def speak(self):
pass
class Tiger(Animal):
def speak(self):
return "Roar!"
class Lion(Animal):
def speak(self):
return "growl!"
def animal_sound(animal):
return animal.speak()
tiger = Tiger()
lion = Lion()
print(animal_sound(tiger)) # Output: Roar!
print(animal_sound(lion)) # Output: growl!
Method Overloading: While Python doesn't support traditional method overloading, you can achieve it using default parameter values or variable-length argument lists (*args, **kwargs). Using this approach, it is possible for a single method to handle different types or counts of arguments.
Example:
Code:
class Myclass:
def product(self, x, y=None):
if y is None:
return x
else:
return x * y
math = Myclass()
print(math.product(7)) # Output: 7
print(math.product(12, 24)) # Output: 288
In the example above, the 'product()' method can handle one or two arguments, demonstrating a form of polymorphism.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-interview/how-is-polymorphism-achieved-in-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics