Polymorphism in Python
Polymorphism is a concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. In Python, polymorphism can be achieved through inheritance and method overriding.
Here is an example of polymorphism in Python:
class Animal: def __init__(self, name): self.name = name def speak(self): pass class Dog(Animal): def speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" dog = Dog("Fido") cat = Cat("Whiskers") print(dog.speak()) print(cat.speak())
The output of the above code will be following
In this example, the Animal class is the superclass. The Dog and Cat classes are subclasses that inherit from Animals. The speak method is defined in the Animals class but overridden in the Dog and Cat classes to return different strings.
The animal_speak function takes an Animal object as an argument and calls the speak method on it. Since the speak method is overridden in the Dog and Cat classes, the function will return different strings depending on the type of object passed to it. This is an example of polymorphism in action.
In python, Polymorphism is also achieved through Duck typing.
def speak(animal): return animal.speak() class Dog: def speak(self): return "Woof!" class Cat: def speak(self): return "Meow!" dog = Dog() cat = Cat() print(speak(dog)) # Output: "Woof!" print(speak(cat)) # Output: "Meow!"
Here, We don’t need to define any class or inheritance; we just need to make sure that the passed object has to speak method, and if it does, it can be used.
In summary, polymorphism in Python allows objects of different classes to be treated as objects of a common superclass by using inheritance and method overriding or by making sure the passed object has the required method.