×

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

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Text detection using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Nested List in Python

The list is an inbuilt sequential data type in Python. It is a very useful and frequently used data type. A list can store any number of data items of...

4 minutes read.

API Requests using Python

What is an API? API stands for Application Programming Interface. It is commonly known as API. It provides an environment that helps two or more computer programs to contact each other....

5 minutes read.

Python Multiprocessing Processor

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

4 minutes read.

Python setattr() function

Python setattr() function The setattr() function sets the value of the specified attribute of the specified object. Syntax setattr(object, name, value) Parameter object: This parameter represents any object. name: This parameter represents the name of the attribute you...

1 minute read.

Python Os sep

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

3 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Classification

Identification and grouping of items or concepts into specified categories this process is known the classification. Data can be separated and sorted in data management according to predetermined criteria for...

6 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

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

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

PyShark in Python

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

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

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.