The Wayback Machine - https://web.archive.org/web/20240921140719/https://www.geeksforgeeks.org/operator-overloading-in-python/
Open In App

Operator Overloading in Python

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading. 

Example

Python3
# Python program to show use of
# + operator for different purposes.

print(1 + 2)

# concatenate two strings
print("Geeks"+"For") 

# Product two numbers
print(3 * 4)

# Repeat the String
print("Geeks"*4)

Output
3
GeeksFor
12
GeeksGeeksGeeksGeeks

How to overload the operators in Python? 

Consider that we have two objects which are a physical representation of a class (user-defined data type) and we have to add two objects with binary ‘+’ operator it throws an error, because compiler don’t know how to add two objects. So we define a method for an operator and that process is called operator overloading. We can overload all existing operators but we can’t create a new operator. To perform operator overloading, Python provides some special function or magic function that is automatically invoked when it is associated with that particular operator. For example, when we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined.

Overloading binary + operator in Python: 

When we use an operator on user-defined data types then automatically a special function or magic function associated with that operator is invoked. Changing the behavior of operator is as simple as changing the behavior of a method or function. You define methods in your class and operators work according to that behavior defined in methods. When we use + operator, the magic method __add__ is automatically invoked in which the operation for + operator is defined. Thereby changing this magic method’s code, we can give extra meaning to the + operator. 

How Does the Operator Overloading Actually work?

Whenever you change the behavior of the existing operator through operator overloading, you have to redefine the special function that is invoked automatically when the operator is used with the objects. 

For Example: 

Code 1:  

Python3
# Python Program illustrate how 
# to overload an binary + operator
# And how it actually works

class A:
    def __init__(self, a):
        self.a = a

    # adding two objects 
    def __add__(self, o):
        return self.a + o.a 
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")

print(ob1 + ob2)
print(ob3 + ob4)
# Actual working when Binary Operator is used.
print(A.__add__(ob1 , ob2)) 
print(A.__add__(ob3,ob4)) 
#And can also be Understand as :
print(ob1.__add__(ob2))
print(ob3.__add__(ob4))

Output
3
GeeksFor
3
GeeksFor
3
GeeksFor

Here, We defined the special function “__add__( )”  and when the objects ob1 and ob2 are coded as “ob1 + ob2“, the special function is automatically called as ob1.__add__(ob2) which simply means that ob1 calls the __add__( ) function with ob2 as an Argument and It actually means A .__add__(ob1, ob2). Hence, when the Binary operator is overloaded, the object before the operator calls the respective function with object after operator as parameter.

Code 2: 

Python3
# Python Program to perform addition 
# of two complex numbers using binary 
# + operator overloading.

class complex:
    def __init__(self, a, b):
        self.a = a
        self.b = b

     # adding two objects 
    def __add__(self, other):
        return self.a + other.a, self.b + other.b

Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
Ob3 = Ob1 + Ob2
print(Ob3)

Output
(3, 5)

Overloading comparison operators in Python :  

Python3
# Python program to overload
# a comparison operators 

class A:
    def __init__(self, a):
        self.a = a
    def __gt__(self, other):
        if(self.a>other.a):
            return True
        else:
            return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
    print("ob1 is greater than ob2")
else:
    print("ob2 is greater than ob1")

Output:

ob2 is greater than ob1

Overloading equality and less than operators: 

Python3
# Python program to overload equality
# and less than operators

class A:
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        if(self.a<other.a):
            return "ob1 is lessthan ob2"
        else:
            return "ob2 is less than ob1"
    def __eq__(self, other):
        if(self.a == other.a):
            return "Both are equal"
        else:
            return "Not equal"
                
ob1 = A(2)
ob2 = A(3)
print(ob1 < ob2)

ob3 = A(4)
ob4 = A(4)
print(ob1 == ob2)

Output:

ob1 is lessthan ob2
Not equal

Python magic methods or special functions for operator overloading

Binary Operators:

OperatorMagic Method
+__add__(self, other)
–__sub__(self, other)
*__mul__(self, other)
/__truediv__(self, other)
//__floordiv__(self, other)
%__mod__(self, other)
**__pow__(self, other)
>>__rshift__(self, other)
<<__lshift__(self, other)
&__and__(self, other)
|__or__(self, other)
^__xor__(self, other)

Comparison Operators:

OperatorMagic Method
<__lt__(self, other)
>__gt__(self, other)
<=__le__(self, other)
>=__ge__(self, other)
==__eq__(self, other)
!=__ne__(self, other)

Assignment Operators:

OperatorMagic Method
-=__isub__(self, other)
+=__iadd__(self, other)
*=__imul__(self, other)
/=__idiv__(self, other)
//=__ifloordiv__(self, other)
%=__imod__(self, other)
**=__ipow__(self, other)
>>=__irshift__(self, other)
<<=__ilshift__(self, other)
&=__iand__(self, other)
|=__ior__(self, other)
^=__ixor__(self, other)

Unary Operators:

OperatorMagic Method
–__neg__(self)
+__pos__(self)
~__invert__(self)

Note: It is not possible to change the number of operands of an operator. For example: If we can not overload a unary operator as a binary operator. The following code will throw a syntax error.

Python
# Python program which attempts to
# overload ~ operator as binary operator


class A:
    def __init__(self, a):
        self.a = a

    # Overloading ~ operator, but with two operands
    def __invert__(self):
        return "This is the ~ operator, overloaded as binary operator."


ob1 = A(2)

print(~ob1)

Output
This is the ~ operator, overloaded as binary operator.

operator overloading on Boolean values:
 

In Python, you can overload the Boolean operators and, or, and not by defining the __and__, __or__, and __not__ special methods in your class.

Here’s an example of how to overload the and operator for a custom class:

Python
class MyClass:
    def __init__(self, value):
        self.value = value

    def __and__(self, other):
        return MyClass(self.value and other.value)

a = MyClass(True)
b = MyClass(False)
c = a & b  # c.value is False

Explanation:

In this example, we define a MyClass that has a single attribute value, which is a boolean. We then overload the & operator by defining the __and__ method to perform a logical and operation on the value attribute of two MyClass instances.

When we call a & b, the __and__ method is called with a as the first argument and b as the second argument. The method returns a new instance of MyClass with a value attribute that is the logical and of a.value and b.value.

Note that Python also provides built-in boolean operators that can be used with any object. For example, you can use the bool() function to convert any object to a boolean value, and the all() and any() functions to perform logical and and or operations on a sequence of boolean values. Overloading the boolean operators in a custom class can be useful to provide a more natural syntax and semantics for your class.

Advantages:

Overloading boolean operators in a custom class can provide several advantages, including:

  1. Improved readability: By overloading boolean operators, you can provide a more natural syntax and semantics for your class that makes it easier to read and understand.
  2. Consistency with built-in types: Overloading boolean operators can make your class behave more like built-in types in Python, which can make it easier to use and integrate with other code.
  3. Operator overloading: Overloading boolean operators is an example of operator overloading in Python, which can make your code more concise and expressive by allowing you to use familiar operators to perform custom operations on your objects.
  4. Custom behavior: Overloading boolean operators can allow you to define custom behavior for your class that is not available in built-in types or other classes.
  5. Enhanced functionality: By overloading boolean operators, you can add new functionality to your class that was not available before, such as the ability to perform logical and or or operations on instances of your class.

Overall, overloading boolean operators in a custom class can make your code more readable, consistent, concise, expressive, and functional. However, it’s important to use operator overloading judiciously and only when it makes sense for the semantics of your class.

Operator Overloading in Python – FAQs

What is the Plus Operator in Python?

The plus operator (+) in Python is primarily used for addition when applied to numbers and for concatenation when applied to strings. It adds integers and floating-point numbers and combines strings or lists into a single sequence.

# Addition
result = 3 + 2
print(result) # Outputs: 5

# Concatenation
greeting = "Hello " + "World"
print(greeting) # Outputs: "Hello World"

What is Operator Overloading in Python?

Operator overloading in Python refers to the ability to change the behavior of operators based on the operands that they act upon. This is done by defining special methods in the class to handle the operator. For instance, you can overload the + operator to add properties of objects or merge custom data structures.

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(2, 3)
result = p1 + p2
print(result.x, result.y) # Outputs: 3

What Are the Different Types of Overloading in Python?

In Python, the concept of overloading extends to:

  1. Operator Overloading: Changing the behavior of operators depending on the operands.
  2. Function Overloading: Python does not support function overloading in the traditional sense, but you can achieve similar functionality by using default parameters or variable-length argument lists.

What Are the 7 Operators in Python?

If by “7 operators,” you mean categories, Python supports several types of operators:

  1. Arithmetic Operators: +, -, *, /, %, ** (exponentiation), // (floor division).
  2. Comparison Operators: ==, !=, <, >, <=, >=.
  3. Logical Operators: and, or, not.
  4. Bitwise Operators: &, |, ^, ~, <<, >>.
  5. Assignment Operators: =, +=, -=, etc.
  6. Identity Operators: is, is not.
  7. Membership Operators: in, not in.

What is +- in Python?

The sequence +- is not a single operator in Python but two consecutive unary operators. The + is the unary plus, and - is the unary minus. When used together in expressions like x = +-y, it effectively applies unary minus, making x the negation of y. This is equivalent to x = -y.



Previous Article
Next Article

Similar Reads

Concatenate two strings using Operator Overloading in Python
Operator Overloading refers to using the same operator to perform different tasks by passing different types of data as arguments. To understand how '+' operator works in two different ways in python let us take the following example C/C++ Code # taking two numbers a = 2 b = 3 # using '+' operator add them c = a+b # printing the result print(&quot;
2 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Method And Constructor Overloading In Python
In object-oriented programming, method, and constructor overloading are powerful features that allow developers to define multiple methods or constructors with the same name but with different parameters. This flexibility enhances code readability, and reusability, and provides a more intuitive interface for developers. In this article, we will lea
4 min read
Python | Method Overloading
Method Overloading: Two or more methods have the same name but different numbers of parameters or different types of parameters, or both. These methods are called overloaded methods and this is called method overloading. Like other languages (for example, method overloading in C++) do, python does not support method overloading by default. But ther
7 min read
Function overloading with singledispatch-functools
Single-dispatch generic function decorator transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation. To add overloaded implementations to the function, use the register() attribute of the generic function. It is a decor
2 min read
Difference between == and is operator in Python
When comparing objects in Python, the identity operator is frequently used in contexts where the equality operator == should be. In reality, it is almost never a good idea to use it when comparing data. What is == Operator?To compare objects based on their values, Python's equality operators (==) are employed. It calls the left object's __eq__() cl
3 min read
Python | Operator.countOf
Operator.countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. Syntax : Operator.countOf(freq = a, value = b) Parameters : freq : It can be list or any other data type which store value value : It is value for which we have to count the number of occurrences Returns: Count of number of occ
2 min read
Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list. Code : Initializing 1D-list list in Python # Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [0]*5 # Initialize using list comprehension # list of size 5 will be
2 min read
Check if a value exists in a DataFrame using in &amp; not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
What does the Double Star operator mean in Python?
Double Star or (**) is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python Language. It is also known as Power Operator. What is the Precedence of Arithmetic Operators? Arithmetic operators follow the same precedence rules as in mathematics, and they are: exponential is performed first, multiplication and division are performed ne
3 min read
Difference between != and is not operator in Python
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Whereas is not operator checks whether id() of two objects is same or not. If same, it returns False and if not same, it returns
3 min read
Create multiple copies of a string in Python by using multiplication operator
In this article, we will see how to create multiple copies of a string by using the multiplication operator(*). Python supports certain operations to be performed on a string, multiplication operator is one of them. Method 1: Simply using multiplication operator on the string to be copied with the required number of times it should be copied. Synta
3 min read
Python MySQL - LIKE() operator
In this article, we will discuss the use of LIKE operator in MySQL using Python language. Sometimes we may require tuples from the database which match certain patterns. For example, we may wish to retrieve all columns where the tuples start with the letter ‘y’, or start with ‘b’ and end with ‘l’, or even more complicated and restrictive string pat
3 min read
Python MySQL - BETWEEN and IN Operator
In this article, we are going to see the database operations BETWEEN and IN operators in MySQL using Python. Both of these operators are used with the WHERE query to check if an expression is within a range or in a list of values in SQL. We are going to use the below table to perform various operations: The SQL BETWEEN condition is used to test if
3 min read
How to use the IN operator in SQLAlchemy in Python?
In this article, we will see how to use the IN operator using SQLAlchemy in Python. We will cover 2 examples, one each for SQLAchemy Core and ORM layers. In both examples, we will count the number of records present in the category table within the sakila database. The sample data from the table looks like. If you do not have sakila database and wa
4 min read
Walrus Operator in Python 3.8
The Walrus Operator is a new addition to Python 3.8 and higher. In this article, we're going to discuss the Walrus operator and explain it with an example. Introduction Walrus Operator allows you to assign a value to a variable within an expression. This can be useful when you need to use a value multiple times in a loop, but don't want to repeat t
2 min read
Difference between / vs. // operator in Python
In this article, we will see the difference between the / vs // operator in Python Python Division OperatorThe division operator '/ ' performs standard division, which can result in a floating-point number. However, if both the dividend and divisor are integers, Python will perform integer division only if the result is an integer. Otherwise, it wi
2 min read
Python NOT EQUAL operator
In this article, we are going to see != (Not equal) operators. In Python, != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Python NOT EQUAL operators SyntaxThe Operator not equal in the Python description: != Not Equal operator, works in both Python
3 min read
not Operator in Python | Boolean Logic
Python not keyword is a logical operator that is usually used to figure out the negation or opposite boolean value of the operand. The Keyword 'not' is a unary type operator which means that it takes only one operand for the logical operation and returns the complementary of the boolean value of the operand. For example, if we give false as an oper
5 min read
Operator Functions in Python | Set 1
Python has predefined functions for many mathematical, logical, relational, bitwise etc operations under the module "operator". Some of the basic functions are covered in this article. 1. add(a, b) :- This function returns addition of the given arguments. Operation - a + b. 2. sub(a, b) :- This function returns difference of the given arguments. Op
5 min read
Operator Functions in Python | Set 2
Operator Functions in Python | Set 1 More functions are discussed in this article. 1. setitem(ob, pos, val) :- This function is used to assign the value at a particular position in the container. Operation - ob[pos] = val 2. delitem(ob, pos) :- This function is used to delete the value at a particular position in the container. Operation - del ob[p
5 min read
Python - Star or Asterisk operator ( * )
There are a many places you’ll see * and ** used in Python. Many Python Programmers even at the intermediate level are often puzzled when it comes to the asterisk ( * ) character in Python. After studying this article, you will have a solid understanding of the asterisk ( * ) operator in Python and become a better coder in the process! Below are th
3 min read
Ternary Operator in Python
In Python, Ternary Operator determines if a condition is true or false and then returns the appropriate value as the result. The ternary operator is useful in cases where we need to assign a value to a variable based on a simple condition, and we want to keep our code more concise — all in just one line of code. It's convenient when we want to avoi
7 min read
Modulo operator (%) in Python
When we see a '%' the first thing that comes to our mind is the "percent" but in computer language, it means modulo operation(%) which returns the remainder of dividing the left-hand operand by right-hand operand or in layman's terms it finds the remainder or signed remainder after the division of one number by another. Given two positive numbers,
4 min read
How to Fix "Could Not Identify an Equality Operator for Type Python JSON"?
When working with JSON data in programming languages like JavaScript or TypeScript we might encounter an error message stating "Could Not Identify an Equality Operator for Type JSON." This error occurs because the JSON objects are not natively comparable using equality operators like == or === in many programming languages. Problem StatementConside
5 min read
Python IF with NOT Operator
We can use if with logical not operator in Python. The main use of the logical not operator is that it is used to inverse the value. With the help of not operator, we can convert true value to false and vice versa. When not applied to the value so it reverses it and then the final value is evaluated by the if condition. So according to its final va
6 min read
Python OR Operator
Python OR Operator takes at least two boolean expressions and returns True if any one of the expressions is True. If all the expressions are False then it returns False. Flowchart of Python OR OperatorTruth Table for Python OR OperatorExpression 1Expression 2ResultTrueTrueTrueTrueFalseTrueFalseTrueTrueFalseFalseFalseUsing Python OR Operator with Bo
4 min read
Operator.length_hint() method in Python
length_hint() method is part of the operator module, which contains a collection of functions that correspond to standard operations and can be useful for functional programming and optimization. How operator.length_hint() WorksThe length_hint() function is designed to interact with objects that implement the __length_hint__ method. This method is
2 min read
New '=' Operator in Python3.8 f-string
Python have introduced the new = operator in f-string for self documenting the strings in Python 3.8.2 version. Now with the help of this expression we can specify names in the string to get the exact value in the strings despite the position of the variable. Now f-string can be defined as f'{expr=}' expression. We can specify any required name in
1 min read
PostgreSQL - IN Operator
The PostgreSQL IN operator is a powerful tool used in conjunction with the WHERE clause to filter records based on a list of values. This operator simplifies queries and enhances readability, making it an essential component of SQL for database manipulation and data retrieval. Let us get a better understanding of the IN operator in PostgreSQL from
3 min read
Article Tags :
Practice Tags :