Python Tutorial Python Advanced Python Resources Python Libraries
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

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)

v1 = Vector(10, 15)
v1 += 5
print("v1 =", v1)

The output of the above code will be:

v1 = (15,20)

❮ Python - Operator Overloading

5