Operator Overloading in Python

Operator Overloading in Python

Operator overloading in Python allows using operators work according to user-defined classes. A new type is created in the code when we create a class and Python allows us to specify the operators with a special meaning which is unique to that data type, this skill is known as operator overloading. For example: we can overload ‘+’ operator to perform string concatenation on two string objects.

 

 

Magic Methods or Dunder Methods in Operator Overloading in Python

In Python, there are some special functions which have __ as prefix and suffix in the name. These functions are known as magic methods or dunder methods. They are automatically called when the operator associated with it used. For example: when ‘+’ operator is used, the magic method __add__ is automatically invoked in which operation for it is already defined. To change the behavior of the operator, magic method should be modified which can be done by defining in a class.

 

 

Example: Overloading + Operator 

# Python program to exemplify overloading + operator

class vector:
  def __init__(self, a, b):
    self.a = a
    self.b = b
  def __str__(self):
    return "({0},{1})".format(self.a, self.b)
  
  #function for overloading + operator
  def __add__(self, other):
    A = self.a + other.a
    B = self.b + other.b
    return vector(A, B)

#creating vector objects
v1 = vector(12. 24)
v2 = vector(15, 25)

#using overloaded + operator 
#on vector objects
v3 = v1 + v2

#displaying the result
print("v3 =", v3)

Output:

v3 = (27,49)

Overloadable Operators in Python

In Python, following operators can be overloaded and they are listed below in the form of tables.

Binary Operators

Operator Magic Method or Dunder Method
+ __add__(self, second)
__sub__(self, second)
* __mul__(self, second)
/ __truediv__(self, second)
// __floordiv__(self, second)
% __mod__(self, second)
** __pow__(self, second)
& __and__(self, second)
| __or__(self, second)
^ __xor__(self, second)
>> __rshift__(self, second)
<< __lshift__(self, second)

Comparison Operators

Operator Magic Method or Dunder Method
< __lt__(self, second)
> __gt__(self, second)
<= __le__(self, second)
>= __ge__(self, second)
== __eq__(self, second)
!= __ne__(self, second)

Assignment Operators

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

Unary Operators

Operator Magic Method or Dunder Method
+ __pos__(self)
__neg__(self)
~ __invert__(self)

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *