Python - Polymorphism

The term "polymorphism" refers to a function or method taking different form in different contexts. Since Python is a dynamically typed language, Polymorphism in Python is very easily implemented.

If a method in a parent class is overridden with different business logic in its different child classes, the base class method is a polymorphic method.


As an example of polymorphism given below, we have shape which is an abstract class. It is used as parent by two classes circle and rectangle. Both classes overrideparent's draw() method in different ways.

from abc import ABC, abstractmethod
class shape(ABC):
   def draw(self):
      "Abstract method"

class circle(shape):
   def draw(self):
      print ("Draw a circle")

class rectangle(shape):
   def draw(self):
      print ("Draw a rectangle")

shapes = [circle(), rectangle()]
for shp in shapes:


When you execute this code, it will produce the following output −

Draw a circle
Draw a rectangle

The variable shp first refers to circle object and calls draw() method from circle class. In next iteration, it refers to rectangle object and calls draw() method from rectangle class. Hence draw() method in shape class is polymorphic.

Kickstart Your Career

Get certified by completing the course

Get Started