What is Polymorphism
Polymorphism is a key concept in object-oriented programming (OOP), and it refers to the ability of objects to take on multiple forms. In Python, polymorphism allows you to define methods in a base class that can be overridden in derived classes, allowing the same method to behave differently in different classes.
There are two main types of polymorphism in Python:
- Method Overriding: This is the ability of a derived class to override a method defined in the base class. To override a method in Python, you simply define a method with the same name in the derived class. The derived class method will then override the base class method.
Here is an example of method overriding in Python:
class Animal:
def make_sound(self):
print("Some generic animal sound")
class Dog(Animal):
def make_sound(self):
print("Bark!")
dog = Dog()
dog.make_sound() # Output: "Bark!"
In this example, the Dog
class overrides the make_sound()
method from the Animal
class, so when you call the make_sound()
method on a Dog
object, it will print "Bark!"
instead of the default "Some generic animal sound"
.
- Method Overloading: This is the ability to define multiple methods with the same name but different arguments. Python does not support method overloading natively, but you can achieve a similar effect using default arguments.
Here is an example of method overloading in Python:
class Calculator:
def add(self, x, y=0):
return x + y
calc = Calculator()
result = calc.add(5, 10) # Output: 15
result = calc.add(5) # Output: 5
In this example, the Calculator
class has a method called add()
that takes two arguments, x
and y
. The y
argument has a default value of 0
, so if you call the add()
method with only one argument, it will use the default value for y
. This allows you to use the same method to add two numbers or to increment a number by a fixed amount.
Polymorphism is a powerful tool in Python, and it allows you to write code that is more flexible and reusable. It's an important concept to understand if you want to take full advantage of the benefits of OOP in Python.
Leave a Comment