Python - Binary Operator Overloading
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.
Operator | Magic 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 example below, 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) #creating vector objects v1 = vector(10, 15) v2 = vector(5, 25) #using overloaded binary operators #on vector objects 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