How can we do Python operator overloading with multiple operands?


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

Updated on: 05-Mar-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements