Python Polymorphism: Adaptable Behavior in Object-Oriented Code

thumb_up 1  ·  sell Python polymorphism, Polymorphic behavior in Python, Implementing polymorphism in Python

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.

Example

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): @abstractmethod def draw(self): "Abstract method" return class circle(shape): def draw(self): super().draw() print ("Draw a circle") return class rectangle(shape): def draw(self): super().draw() print ("Draw a rectangle") return shapes = [circle(), rectangle()] for shp in shapes: shp.draw()

Output

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.

 

 

The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back