×

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

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Explain sklearn clustering in Python

Make a connection and patterns across datasets by using clustering, one of the unsupervised machine learning approaches. Grouping is crucial because it ensures unlabelled data's natural clustering. The sample from...

7 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

StandardScaler in Sklearn

When and How Should You Use StandardScaler? StandardScaler comes into play whenever the properties of the provided dataset change significantly within their ranges or are recorded in different measurement units. Since using...

4 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Python Comments

In this tutorial, we will discuss the importance of comments in the Python code and how various types of comments can be inserted in the code. Comments are used to describe...

3 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

Python List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Python hasattr() function

Python hasattr() function The hasattr() function in Python returns a Boolean value ‘True’ if the given object has the specified attribute, else it returns False. Syntax hasattr(object, name) Parameter object: it is a required parameter which represents an object. attribute:...

1 minute read.