Change language

Operator overloading in Python

# Python program to show usage
# + operator for different purposes.

 

print ( 1 + 2 )

 
# concatenate two lines

print ( "Geeks" + "For"

 
Product # two numbers

print ( 3 * 4 )

 
# Repeat line

print ( " Geeks " * 4 )

Exit :

 3 GeeksFor 12 GeeksGeeksGeeksGeeks 

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

Python binary + operator overloading:
When we use an operator for user-defined data types, the special function or magic function associated with that operator is automatically called. Changing the behavior of an operator is as simple as changing the behavior of a method or function. You define methods in your class, and the operators behave according to the behavior defined in the methods. When we use the + operator, the magic method __add__ is automatically called, which defines the operation for the + operator. There, by changing the code of this magic method, we can give additional meaning to the + operator. 
Code 1:

# Python program illustrates how
# overload binary + operator

 

class A:

def __ init __ ( self , a):

self . a = a

 

# add two objects

  def __ add __ ( self , o):

  return self . a + oa 

ob1 = A ( 1 )

ob2 = A ( 2 )

ob3 = A ( "Geeks" )

ob4 = A ( " For " )

 

print (ob1 + ob2)

print (ob3 + ob4)

Output:

 3 GeeksFor 

Code 2:

# Python program to do the addition
# two complex numbers using binary numbers
# + operator overloading.

 

class complex :

  def __ init__ ( self , a, b):

self . a = a

  self . b = b

 

  # add two objects

def __ add __ ( self , other):

return self . a + other.a, self . b + other.b

 

def __ str __ ( self ):

  return self . a, self . b

 

Ob1 = complex ( 1 , 2 )

Ob2 = complex ( 2 , 3

Ob3 = Ob1 + Ob2

print (Ob3)

Exit:

 (3, 5) 

Python comparison operator overloading:

# Python program to overload
# 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:

# Python program to overload equality # and less than statements

 

class A:

def __ init __ ( self , a):

self . a = a

def __ lt __ ( self , other):

if ( self . a "other.a):

  return "ob1 is les sthan 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 & lt; 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 :

Operator Magic Method
+ __add __ (self, other)
- __sub __ (self, other)
* __mul __ (self, other)
/ __truediv __ (self, other)
// __floordiv __ (self, other)
% __mod __ (self, other)
** __pow __ (self, other)

Comparison operators:

Operator Magic Method
& lt;  __lt __ (self, other)
" __gt __ (self , other)
"= __le __ (self, other)
" = __ge __ (self, other)
== __eq __ (self, other)
! = __ne __ (self, other)

Assignment Operators:

Operator Magic Method >
- = __isub __ (self, other)
+ = __iadd __ (self, other)
* = __imul__ (self, other)
/ = __idiv __ (self, other)
// = __ifloordiv __ (self, other)
% = __imod __ (self, other)
** = __ ipow __ (self, other)

Unary operators:

Operator Magic Method
- __neg __ (self, other)
+ __pos __ (self, other)
~ __invert __ (self, other)

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically