Language: EN

polimorfismo-en-python

How to Use Polymorphism in Python

Polymorphism is the ability of an object to take different forms depending on the context.

In Python, this is achieved through “duck typing,” which basically means that the behavior of an object is determined by its behavior, rather than its specific type.

Let’s see it with an example. Suppose we have our class Person.

# Definition of the Person class
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def greet(self):
        print(f"Name: {self.name}, Age: {self.age}")

And one or more derived classes

# Definition of the Teacher class that inherits from Person
class Teacher(Person):
    def __init__(self, name, age):
        super().__init__(name, age)        
    
    def greet(self):
        print("I am a teacher")
        
# Definition of the Student class that inherits from Person
class Student(Person):
    def __init__(self, name, age):
        super().__init__(name, age)        
    
    def greet(self):
        print("I am a student")

On the other hand, suppose we have a function that receives a parameter

# Function that uses polymorphism
def print_information(person):
    person.greet()

Now, we create two instances of Teacher and Student respectively, and pass them to the print_information method.

# Create instances of Teacher and Student
teacher = Teacher("Maria", 30)
student = Student("Luis", 20)

# Use polymorphism
print_information(teacher)     # Prints 'I am a teacher'
print_information(student)  # Prints 'I am a student'

In this example,

  • The function print_information can accept objects from both the Person class and the Student or Teacher class.
  • The function calls the greet method of each object

That is, basically Python “doesn’t care” about the type of the object you pass. If it has the methods, the function will call the method that the object has.


It doesn’t care about its type, or whether they inherit from a class or not. It only cares if it has the methods it needs.