×

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding two separate strings into a single string, and + is used to achieve this. If we say, “Hi” + “ ” + "people", we will get "Hi people" as the output. To concatenate strings, we use the same operator, which is used to add numbers; this is operator overloading. Also, we can use + to add two lists. It is only one operator-"+", but it behaves differently in different scenarios depending on the data type of the operands. This article discusses Operator overloading in detail with examples.

What is Operator Overloading?

As in method overloading, the same method can show different behavior depending on the number of parameters and the data types of the parameters. Operator overloading works on similar concept if you are aware of method overloading in object-oriented programming. Therefore, the feature in Python that allows an operator to behave differently according to the scenario and the data type of the participating operands is called "Operator overloading".

Note: Remember that we can't create new operators in this feature. We can let an already existing operator work on data types it usually can't.

How to Overload an Operator in Python?

How does the compiler know what to do with it when we use an operator? In Python, every in-built operator has a specific magic function. These are the special functions. Whenever the user uses an operator, the method associated with the operator will be automatically called, and the compiler will understand what to do.

For example, in the case of the addition operator, the + operator's magic function is overloaded by both integer class and string class. Hence, + shows different behavior for objects of integer class and string class objects.

Extending The Capabilities of Operators:

Suppose we have a class and created two objects, obj1, and obj2. If we try to use the + operator to add these two objects, it won't be valid, and the compiler will raise an error because adding two objects is not defined in the __add__ (), which is the magic method of +. It is like calling the method with no logic we need. So, we need to create the logic.

Hence, to extend the operator's functionality, we need to write the logic in the magic method of the operator.

class addition:
    def __init__(self, num):
        self. num = num
    def __add__(self, obj):
        return self. num + obj. num
obj1 = addition (2)
obj2 = addition (4)
print ("Sum of the two int objects: ", obj1 + obj2)
obj3 = addition ("Hi")
obj4 = addition ("!")
print ("Sum of two string objects: ", obj3 + obj4)

Output:

Sum of the two int objects:  6

Sum of two string objects:  Hi!

Understanding:

Inside the class, you can see the __add__ method, which is the magic function of the addition operator. We are writing the logic to add two objects to the function in the above program.

In the snippet:

    def __add__(self, obj):
        return self. num + obj. num

When we call + by saying obj1 + obj2, the compiler will automatically invoke this method.

obj1 takes the place of self, and obj2 takes the place of obj:

obj1. num + obj2. num = 2 + 4 = 6 will be the output.

  • Let us extend the logic further to add two complex numbers:
class complex_addition:
    def __init__(self, real, imag):
        self. real = real
        self. imag = imag
    def __add__(self, obj):
        return self. real + obj. real, self. imag + obj. imag
obj1 = complex_addition (3, 4)
obj2 = complex_addition (4, 7)
print ("Sum of the two complex objects: ", obj1 + obj2)

Output:

Sum of the two complex objects:  (7, 11)

Understanding:

To add two complex numbers, we have to add the real part of the two numbers and the imaginary part of the two numbers:

A + iB + C + iD = (A + C) + (B + D)i

  • The multiplication operator * can be used to multiply two or more numbers, and also, when the operands are of the string class, it can be used for repetition or strings:

7 * 8 = 56

Hi * 4 = HiHiHiHi

Now, let us try to overload the comparison operators:


class comparison:
    def __init__(self, num):
        self. num = num
    def __lt__(self, obj):
        if (self. num < obj. num):
            return True
        else:
            return False
    def __gt__ (self, obj):
        if (self. num > obj. num):
            return True
        else:
            return False
    def __eq__ (self, obj):
        if (self. num == obj. num):
            return True
        else:
            return False
obj1 = comparison (int (input ("Enter obj1 value: ")))
obj2 = comparison (int (input ("Enter obj2 value: ")))
print ("Is obj1 greater than obj2? ->", obj1 > obj2)
print ("Is obj1 less than obj2? ->", obj1 < obj2)
print ("Is obj1 equal to obj2? ->", obj1 == obj2)


Output:

Enter obj1 value: 4

Enter obj2 value: 2

Is obj1 greater than obj2? -> True

Is obj1 less than obj2? -> False

Is obj1 equal to obj2? -> False

Understanding:

We took the input for the values of two objects from the user. We wrote logic to compare the values using three magic functions of greater than, less than, and equal to operators in the class.

Here is the list of magic functions of a few operators in Python:

  • BINARY:
OperatorOperationMagic method
+Addition__add__ (self, other)
-Subtraction__sub__ (self, other)
*Multiplication__mul__ (self, other)
/Division__truediv__ (self, other)
//Floor division__floordiv__ (self, other)
%Modulo division__mod__ (self, other)
**Power (Exponent)__pow__ (self, other)
>> Right shift__rshift__ (self, other)
<< Left shift__lshift__ (self, other)
&AND__and__ (self, other)
|OR__or__ (self, other)
^XOR__xor__ (self, other)
  • COMPARISON:
OperatorOperationMagic method
Less than__lt__ (self, other)
Greater than__gt__ (self, other)
<=Less than or equal to__le__ (self, other)
>=Greater than or equal to__ge__ (self, other)
==Equal to__eq__ (self, other)
!=Not equal to__ne__ (self, other)
  • UNARY:
OperatorOperationMagic method
+Positive__pos__ (self)
-Negative__neg__ (self)
~Complement__invert__ (self)
  • Assignment:
OperatorOperationMagic method
+=Add and assign__iadd__ (self, other)
-=Subtract and assign__isub__ (self, other)
*=Multiply and assign__imul__ (self, other)
/=Divide and assign__idiv__ (self, other)
//=Floor divide and assign__ifloordiv__ (self, other)
%=Modulo divide and assign__imod__ (self, other)
**=Power and assign__ipow__ (self, other)
>>=Right shift and assign__irshift__ (self, other)
<<=Left shift and assign__ilshift__ (self, other)
&=AND and assign__iand__ (self, other)
|=OR and assign__ior__ (self, other)
^=XOR and assign__ixor__ (self, other)

Note:

We cannot change the number of operands of an operator. We cannot make a unary operator binary and vice versa. If we try to do so, the compiler will raise an error.

Example: 6~8 is not valid.

Conclusion:

Every time we use an operator, the magic function associated with the operator will be automatically invoked by the compiler. If we want to extend the operator's functionality, we can overload the function using the inbuilt syntax of the special Python functions.


Related Topics

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

_name_ in Python

Introduction: The code at level 0 indentation is to be performed when the command to run a Python program is supplied to the interpreter because Python does not have a main() function...

4 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.

Python Continue Statement

In Python, loops automate and repeat processes in a cost-effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration, or ignore the...

3 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

Python Variable Scope with Local & Non-local Examples

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute read.

Working with CSV files in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

7 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python List remove() method

Python List remove() method The list.remove () method in Python removes the item at the specified position in the given list. Syntax list.remove(x) Parameter x: This parameter represents the element you want to remove and accepts any type...

1 minute read.

Sklearn in Python

Scikit-learn or sklearn is a machine learning library used in Python that provides many unsupervised and supervised learning tools and algorithms. David Cournapeau first created it as a 2007 Google...

7 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.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Sentence to python vector

Conversion of a Sentence to Vector in Python Before starting the tutorial, let’s just recap about the vector and the respective package that has to be imported in Python. Python Vector: Putting simply,...

3 minutes read.