How can we do Python operator overloading with multiple operands?

PythonProgramming

You can do Python operator overloading with multiple operands just like you would do it for binary operators. For example, if you want to overload the + operator for a class, you'd do the following −

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 give the output −

17 + 17i
raja
Published on 19-Apr-2018 15:28:18
Advertisements