Python Tutorials · Python Polymorphism

Python Polymorphism

Learn all about Python Polymorphism in this comprehensive tutorial.

5 min read advanced
  • The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.
  • An example of a Python function that can be used on different objects is the len() function.
  • Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.
  • What about classes with child classes with the same name?

Introduction

The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.

Function Polymorphism

An example of a Python function that can be used on different objects is the len() function.

For strings len() returns the number of characters:

python

For tuples len() returns the number of items in the tuple:

python

For dictionaries len() returns the number of key/value pairs in the dictionary:

python

Class Polymorphism

Polymorphism is often used in Class methods, where we can have multiple classes with the same method name.

For example, say we have three classes: Car, Boat, and Plane, and they all have a method called move():

python

Look at the for loop at the end. Because of polymorphism we can execute the same method for all three classes.

Inheritance Class Polymorphism

What about classes with child classes with the same name? Can we use polymorphism there?

Yes. If we use the example above and make a parent class called Vehicle, and make Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle methods, but can override them:

python

Child classes inherits the properties and methods from the parent class.

In the example above you can see that the Car class is empty, but it inherits brand, model, and move() from Vehicle.

The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but they both override the move() method.

Because of polymorphism we can execute the same method for all classes.

Module quiz

2 questions
1

Which of the following is true about Python Polymorphism?

2

What is the most common pitfall when working with Python Polymorphism?

Answer all questions to submit.