Polymorphism is a key concept in object-oriented programming that allows objects of different types to be treated as instances of a common superclass or interface. It enables the same method name to be used for different objects, and the appropriate method is invoked dynamically based on the object’s type during runtime.
In Python, polymorphism is achieved through method overriding and method overloading.
- Method Overriding: Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its superclass. The overridden method in the subclass has the same name and signature (parameters) as the method in the superclass. When a method is called on an object, Python determines at runtime which implementation to use based on the actual type of the object.
Here’s an example of method overriding in Python:
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): print("Dog barks") class Cat(Animal): def sound(self): print("Cat meows") animal = Animal() animal.sound() # Output: "Animal makes a sound" dog = Dog() dog.sound() # Output: "Dog barks" cat = Cat() cat.sound() # Output: "Cat meows"
- Method Overloading: Method overloading refers to defining multiple methods with the same name but different parameters in the same class. However, Python does not support method overloading in the same way as some other languages like Java or C++. Instead, Python achieves similar functionality by using default parameter values or using variable arguments.
Here’s an example:
class Calculator: def add(self, x, y): return x + y def add(self, x, y, z): return x + y + z calculator = Calculator() print(calculator.add(2, 3)) # Output: TypeError: add() missing 1 required positional argument: 'z' print(calculator.add(2, 3, 4)) # Output: 9
In Python, when we define multiple methods with the same name in a class, the last defined method will override the previous ones. Therefore, attempting to call the
add() method with two arguments will raise a
TypeError because the method with three arguments is the only one available.
To achieve similar behavior to method overloading in Python, you can use default parameter values or utilize variable arguments like
Overall, polymorphism in Python allows you to write flexible and reusable code by treating objects of different types uniformly through inheritance, method overriding, and other language features.