How to do multi-operand operator overloading in Python?
How to Overload Operators with Multiple Operands in Python?
You can use multi-operand operator overloading in Python, just like you can overload operators with two operands. For example, if you want to overload the + operator for a class, you can do so as follows –
Example
class Complex(object):
def __init__(self, real, imag):
self.real = real
self.imag = imag
def __add__(self, other):
real = self.real + other.real
imag = self.imag + other.imag
return Complex(real, imag)
def display(self):
print(str(self.real) + " + " + str(self.imag) + "i")
a = Complex(10, 5)
b = Complex(5, 10)
c = Complex(2, 2)
d = a + b + c
d.display()
Output
This will produce the following output –
17 + 17i
For more Python-related articles, please read: Python Tutorial