What is Python polymorphism?
Polymorphism is a programming concept that allows objects of different types to respond to the same message in different ways. This is achieved by using inheritance and method overriding.
Example:
Python
class Animal:
"""A class to represent an animal."""
def speak(self):
pass
class Dog(Animal):
"""A class to represent a dog."""
def speak(self):
print("Woof!")
class Cat(Animal):
"""A class to represent a cat."""
def speak(self):
print("Meow!")
# Create a dog object
my_dog = Dog()
# Create a cat object
my_cat = Cat()
# Call the speak method on each object
my_dog.speak()
my_cat.speak()
Output:
Woof!
Meow!
In this example, both the Dog and Cat classes inherit from the Animal class. The speak() method is an abstract method in the Animal class, which means that it must be implemented by all subclasses of the Animal class. The Dog and Cat classes implement the speak() method in different ways, depending on the type of animal.
Another example:
Python
class Shape:
"""A class to represent a shape."""
def draw(self):
pass
class Circle(Shape):
"""A class to represent a circle."""
def draw(self):
print("Drawing a circle...")
class Square(Shape):
"""A class to represent a square."""
def draw(self):
print("Drawing a square...")
# Create a circle object
my_circle = Circle()
# Create a square object
my_square = Square()
# Call the draw method on each object
my_circle.draw()
my_square.draw()
Output:
Drawing a circle...
Drawing a square...
In this example, the Circle and Square classes inherit from the Shape class. The draw() method is an abstract method in the Shape class, which means that it must be implemented by all subclasses of the Shape class. The Circle and Square classes implement the draw() method in different ways, depending on the type of shape.
Benefits of using Python polymorphism
Polymorphism has several benefits, including:
Conclusion
Python polymorphism is a powerful tool that can help you to write more efficient, reusable, and maintainable code. By understanding how to use Python polymorphism, you can become a better Python programmer.