Facebook Page Twitter Page LinkedIn Page
× Python Tutorial Python Advanced Python Resources Python Libraries


Binary operators are those operators which requires two operand to produce a new value. Following is the list of binary operators and corresponding magic methods that can be overloaded in Python.

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)

Example: Overloading Binary Operators

In the below example, binary operators: +, -, *, and / are overloaded. When it is applied with vector objects, it performs addition, subtraction, multiplication and division component wise. For example:

  • (10, 15) + (5, 25) will produce (10+5, 15+25) = (15, 40)
  • (10, 15) - (5, 25) will produce (10-5, 15-25) = (5, -10)
  • (10, 15) * (5, 25) will produce (10*5, 15*25) = (50, 375)
  • (10, 15) / (5, 25) will produce (10/5, 15/25) = (2, 0.6)
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)
  
  #function for operator overloading -
  def __sub__(self, other):
    X = self.x - other.x
    Y = self.y - other.y
    return Vector(X, Y)
  
  #function for operator overloading *
  def __mul__(self, other):
    X = self.x * other.x
    Y = self.y * other.y
    return Vector(X, Y)
  
  #function for operator overloading /
  def __truediv__(self, other):
    X = self.x / other.x
    Y = self.y / other.y
    return Vector(X, Y)    

v1 = Vector(10, 15)
v2 = Vector(5, 25)

print("v1 + v2 =", v1+v2)
print("v1 - v2 =", v1-v2)
print("v1 * v2 =", v1*v2)
print("v1 / v2 =", v1/v2) 

The output of the above code will be:

v1 + v2 = (15,40)
v1 - v2 = (5,-10)
v1 * v2 = (50,375)
v1 / v2 = (2.0,0.6)

❮ Python - Operator Overloading