Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

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.



ADVERTISEMENT
ADVERTISEMENT