Python Tutorial Python Advanced Python References Python Libraries

Python - Assignment Operator Overloading



Assignment operator is a binary operator which means it requires two operand to produce a new value. Following is the list of assignment operators and corresponding magic methods that can be overloaded in Python.

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

Example: overloading assignment operator

In the example below, assignment operator (+=) is overloaded. When it is applied with a vector object, it increases x and y components of the vector by specified number. for example - (10, 15) += 5 will produce (10+5, 15+5) = (15, 20).

class vector:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  def __str__(self):
    return "({0},{1})".format(self.x, self.y)
  
  #function for operator overloading +=
  def __iadd__(self, other):
    X = self.x + other
    Y = self.y + other
    return vector(X, Y)

#creating vector object
v1 = vector(10, 15)

#using overloaded += operator 
#with vector object
v1 += 5

#displaying result
print("v1 =", v1)

The output of the above code will be:

v1 = (15,20)

❮ Python - Operator Overloading