C++ - Q&A

Python - Dunder or Magic Methods



Python provides some special function having __ as prefix and suffix in the name, which is also known as Magic method or Dunder method. This function is automatically invoked when the associated operator is used. For example, when + is used, the magic method __add__ is automatically invoked in which the operation for + operator is defined.

A Dunder method is generally used for operator overloading. To change the behavior of the operator, the magic method should be changed which can achieved by defining the magic method in the class.

Overloadable operators in Python

Following is the list of operators and Dunder methods that can be overloaded in Python.

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)
&__and__(self, other)
|__or__(self, other)
^__xor__(self, other)
>>__rshift__(self, other)
<<__lshift__(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
+=__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)

Unary Operators

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

Example:

The example below describes how to overload + operator to add two vectors. To change the behavior of + operator, magic method __add__ is defined in the class as shown in the example. In the example, the vector v1 is taken as (10, 15) and vector v2 is taken as (5, 25). The addition operation of v1 and v2 creates v3 which returns (10+5, 15+25) or (15, 40).

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 __add__(self, other):
    X = self.x + other.x
    Y = self.y + other.y
    return Vector(X, Y)

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

The output of the above code will be:

v3 = (15,40)