Polymorphism is a fundamental concept in object-oriented programming that allows objects of different classes to be treated as if they were the same type. In Python, polymorphism is achieved through method overriding and method overloading.
Method overriding occurs when a subclass provides a different implementation of a method that is already defined in its parent class. This allows objects of the subclass to be used in place of objects of the parent class.
Here is an example of method overriding in Python:
python # Define a parent class class Animal: def speak(self): print("I am an animal.") # Define a child class that overrides the speak() method class Dog(Animal): def speak(self): print("Woof!") # Define another child class that overrides the speak() method class Cat(Animal): def speak(self): print("Meow!") # Create objects of the child classes my_dog = Dog() my_cat = Cat() # Call the speak() method of the objects my_dog.speak() # Output: "Woof!" my_cat.speak() # Output: "Meow!"
In this example, a parent class called `Animal` is defined with one method (`speak()`). Two child classes called `Dog` and `Cat` are defined that override the `speak()` method with their own implementations. Objects of the `Dog` and `Cat` classes are created and their `speak()` methods are called, which output different messages to the console.
Method overloading occurs when a class provides multiple methods with the same name but different parameters. This allows the same method name to be used for different operations.
In Python, method overloading is achieved through default arguments and variable-length arguments. Here is an example:
python # Define a class with two overloaded methods class Calculator: def add(self, a, b): return a + b def add(self, a, b, c=0): return a + b + c def add(self, *args): return sum(args) # Create an object of the class my_calculator = Calculator() # Call the overloaded methods of the object print(my_calculator.add(2, 3)) # Output: 5 print(my_calculator.add(2, 3, 4)) # Output: 9 print(my_calculator.add(2, 3, 4, 5, 6)) # Output: 20
In this example, a class called `Calculator` is defined with three overloaded methods called `add()`. The first method takes two arguments, the second method takes three arguments (with the third argument having a default value of 0), and the third method takes a variable number of arguments using the `*args` syntax. An object of the `Calculator` class is created and its `add()` methods are called with different numbers of arguments, which perform addition operations and output the results to the console.
Polymorphism is a powerful feature of Python and is used extensively in object-oriented programming to create flexible and reusable code.