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 determines its functionality, rather than its specific type.
Let’s see it with an example. Suppose we have our 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}")
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 we pass them to the print_information
method.
# Create instances of Teacher and Student
teacher = Teacher("Maria", 30)
student = Student("Juan", 20)
# Use polymorphism
print_information(teacher) # Prints 'I am a teacher'
print_information(student) # Prints 'I am a student'
In this example,
- The
print_information
function can accept objects of both thePerson
class and theStudent
orTeacher
class. - The function calls the
greet
method of each object.
In other words, 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 matter what its type is, or whether it inherits from a class or not. It only cares if it has the methods it needs.