Polymorphism in Python
Polymorphism in Python
Method overriding is the process of defining a method in a subclass that has the
same name as a method in the superclass. When an object of the subclass is
created, it can be treated as if it were an object of the superclass, and the
overridden method will be called instead of the superclass method.
ruby
Copy code
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError('Subclass must implement abstract method')
class Dog(Animal):
def speak(self):
return 'Woof!'
class Cat(Animal):
def speak(self):
return 'Meow!'
class Cow(Animal):
def speak(self):
return 'Moo!'
We then define three subclasses of Animal (Dog, Cat, and Cow), each of which
implements its own speak() method.
Finally, we create a list of Animal objects (animals) that includes one instance
of each subclass, and we loop over the list and call the speak() method on each
object. Since each object is an instance of a different subclass, the speak()
method will behave differently for each object, demonstrating the principle of
polymorphism.
In this way, polymorphism allows us to write more flexible and reusable code,
since we can treat objects of different types as if they were the same type,
as long as they implement the same methods.