Polymorphism is the ability to take many forms, for example, if the parent class has a method named ABC, it means that the child class can have a method with the same name ABC, containing its own parameters and variables, in python It can be achieved without any affectation or setback in the execution.
Python's point of view is difficult to explain without talking about duck typing , so we recommend reading it.
Being a dynamically typed language and allowing duck typing, in Python it is not necessary for the objects to share an interface, it is simply enough that they have the methods that they want to call.
Suppose we have an Animal class with a hablar() method.
class Animal: def hablar(self): pass On the other hand we have two other classes, Perro , Gato that inherit from the previous one. Also, they implement the hablar() method in a different way.
class Perro(Animal): def hablar(self): print("Guau!") class Gato(Animal): def hablar(self): print("Miau!") We then create an object of each class and call the hablar() method. We can see that each animal behaves differently when using hablar() .
for animal in Perro(), Gato(): animal.hablar() # Guau! # Miau! In the previous case, the animal variable has been “taking the forms” of Perro and Gato . However, note that by having dynamic typing this example would have worked the same without inheritance between Perro and Gato , but we leave this explanation for the chapter on duck typing