Polymorphism in Python

Learn about polymorphism in Python to understand how methods can be customized to behave differently based on the objects they operate on.

In object-oriented programming, polymorphism is a key concept which enables a function or object to take on different forms and act differently based on the context. Let's understand this with the following analogy.

Suppose a person is a teacher, a coach, and a parent. Even though it's the same person, they will act differently based on the role they have assumed at a particular time. As a teacher they educate students on some subject, as a coach they might coach a sports team in the evening, and as a Parent they will take care of their children and maybe help with the homework.

Polymorphism enhances code flexibility and reusability.

Types of polymorphism

There are two types of polymorphism:

  • Compile time polymorphism or static polymorphism

  • Runtime polymorphism or dynamic polymorphism

Compile time polymorphism

Compile time polymorphism is achieved through method overloading. In Python, method overloading isn't supported in the traditional sense, i.e., having multiple methods having the same name but each having a different number of parameters. However, we can achieve similar results using default arguments as shown in the playground below.

Get hands-on with 1200+ tech skills courses.