Overloaded Operators

An overloaded operator is defined as a strangely-named method of a class:

class complex:
   def __init__ (self, re = 0.0, im = 0.0):
      self.re = re
      self.im = im
   def __add__ (self, other): # self + other
      return complex (self.re + other.re,
                      self.im + other.im)
x = complex (7.0, -7.0) + complex (1.0)
print x.re, x.im
# result: 8.0 -7.0
New Models for Processing Text and XML with Python Sam Wilmott
Slide 9 of 51        www.wilmott.ca