×

Polymorphism in Python

What is polymorphism and why is it important?

Polymorphism's literal definition is the state of occurring in diverse shapes or forms.

When it comes to programming, the idea of polymorphism is crucial. Using a same type entity (method, operator, or object) to represent multiple types in various contexts is known as polymorphism.

How about the following example:

A polymorphism in the addition operator as an example

The Plus operator is widely used in Python applications, as we all know. However, it has no one use.

+ Operator is used for integer data types to perform arithmetic addition.

SYNTAX

num1 = 1
num2 = 2
print(num1+num2)

This is why program produces 3 in this case.

Concatenation is performed using the + operator for string data types.

SYNTAX

str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)

Python Programming is the consequence of the above code.

Using the + operator, we can observe that various operations have been performed on distinct data types. This is one of the simplest examples of polymorphism in Python that I've come across thus far.

Polymorphism of Python functions

Some Python functions may be used with a variety of data types.

len() is an example of such a function. Python allows you to execute it with a wide variety of data types. Let's have a look at a few examples of how the function may be used.

Function len() using polymorphism as an example

SYNTAX

print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))

OUTPUT

9
3
2

We can see that the len() method can operate with a wide variety of data types, including text, list, tuple, set, and dictionary. On the other hand we can see that it only delivers information about particular data kinds.

Polymorphism of classes in the Python programming language

As far as object-oriented programming is concerned, polymorphism is a crucial notion.

Python Object-Oriented Programming is a great resource for learning more about OOP in Python.

Class methods can take use of polymorphism since Python enables distinct classes to have methods that have the same name. In the future, we may extend the use of these methods by not caring about the object we're dealing with. Let's have a look at a specific case:

Class Method Polymorphism next example

SYNTAX

class Cat:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def info(self):
        print(f"I am a cat. My name is {self.name}. I am {self.age} years old.")
    def make_sound(self):
        print("Meow")
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def info(self):
        print(f"I am a dog. My name is {self.name}. I am {self.age} years old.")
    def make_sound(self):
        print("Bark")
cat1 = Cat("Kitty", 2.5)
dog1 = Dog("Fluffy", 4)
for animal in (cat1, dog1):
    animal.make_sound()
    animal.info()
    animal.make_sound()

Output:

Meow
I am a cat. My name is Kitty. I am 2.5 years old.
Meow
Bark
I am a dog. My name is Fluffy. I am 4 years old.
Bark

There are two classes in this game: Cat and Dog. info() and make sound are identical in structure and have the same method names ().

Observe, however, that we haven't built a common superclass or connected the classes in any manner together. But even in that case, we may combine these two objects into one tuple and iterate through it using a common animal variable to keep track of the results. Polymorphism makes it feasible.

Polymorphism and Inheritance

Child classes inherit methods and properties from the parent class in Python, just as they do in most other programming languages. Method Overriding allows us to modify particular methods and properties explicitly for the child class.

As a result of polymorphism, we are able to access overridden methods and attributes that have the same name as their parent.

Let's have a look at a specific case:

from math import pi
class Shape:
    def __init__(self, name):
        self.name = name
    def area(self):
        pass
    def fact(self):
        return "I am a two-dimensional shape."
    def __str__(self):
        return self.name
class Square(Shape):
    def __init__(self, length):
        super().__init__("Square")
        self.length = length
    def area(self):
        return self.length**2
    def fact(self):
        return "Squares have each angle equal to 90 degrees."
class Circle(Shape):
    def __init__(self, radius):
        super().__init__("Circle")
        self.radius = radius
    def area(self):
        return pi*self.radius**2
a = Square(4)
b = Circle(7)
print(b)
print(b.fact())
print(a.fact())
print(b.area())

Related Topics

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

How to Practice Python Programming

Learning python kkis a step towards coding. Python gets one closer to programming languages. It is essential to practice every programming language to become a professional in coding. It is...

4 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python String lower() method

Python String lower() method The string.lower() method in Python returns a string where all characters are lower case. Syntax string.lower() Parameter NA Return This method returns a string where all characters are lower case. Example 1 # Python...

1 minute read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

NOT IN operator in Python

This page contains all the information about “not in” operator in python. You can also know everything about what type of operator is “not in” in python language and where...

7 minutes read.

How to Add Elements in List in Python?

How to Add Elements in List in Python We all are aware of the wide spectrum of applications where the data structures of Python are used. Be it lists, tuples, or...

4 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Operator Module In Python

Introduction The operator module is used for performing operations using methods rather than utilizing operators in Python code. The operator module provides several methods for performing the operations.  The operator module contains...

7 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

Speech Recognition in Python

What is Speech Recognition? Speech Recognition is a term defined for automatic recognition of human speech. Speech recognition is the most significant activity in the domain of the interaction between the...

8 minutes read.

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players The object of Keyboard Jump (hop) Game Python Project is to fabricate...

7 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

How to create a DataFrames in Python

How to create a DataFrames in Python Data Frame is a data structure in which data is stored in tabular form. They can also be referred as two-dimensional collection of data. Various...

5 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

How to get Time in seconds in Python

Python's time module source shows that are based on time. The time() method is used by developers and returns the current time as a UNIX timestamp. A UNIX timestamp is...

4 minutes read.