polimorfismo-en-python

How to Use Polymorphism in Python

  • 2 min

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 an object’s behavior is determined by its actions, rather than its specific type.

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

# 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}")
Copied!

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")
Copied!

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

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

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'
Copied!

In this example,

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

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

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