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}")
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
print_informationfunction can accept objects from both thePersonclass and theStudentorTeacherclasses. - The function calls the
greetmethod 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.
