×

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

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 ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Python md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Gaussian elimination in python

Linear and polynomial equations are used in almost all fields of numerical simulation. However, its most common use in engineering is in the area of linear system analysis. The broader...

3 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Python md5() function

Python md5() function The md5() function in PHP calculates the md5 hash of a string. Syntax md5 ( string $str [, bool $raw_output] ) Parameter str(required)- This parameter specifies the string. raw_output(optional)- This parameter specifies a hex or binary output format: TRUE - Raw 16 character binary...

1 minute read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Python bin() function

Python bin() function The bin() function in Python returns the binary version for the specified integer. Syntax bin(x) Parameter n: This parameter represents an integer or int value. Return This function returns a binary string for the specified integer...

1 minute read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

How to reverse a string in python

How to reverse a string in python A Brief About Strings- The String is a data type in Python that has a sequence of characters. This series of characters are represented in...

4 minutes read.

N2 in Python

N2 is known as Nearest Neighbor Algorithm, because it contains 2 N's (N-Nearest, N-Neighbor). This is a library in the python build using C++ and Python. Before N2 was made,...

3 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Python Program to Check Leap Year

Python Program to Check Leap Year Leap year: We all know that each year has 365 or 366 days. But whenever a year has 366 days, then the year is said...

2 minutes read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.