Advertisement
cwchen

Operator overloading demo in Python 2

Feb 10th, 2016
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. # Just for demo.  DON'T DO THIS IN PRODUCTION CODE.
  2.  
  3. class MyComplex(object):
  4.     def __init__(self, real=0, imag=0):
  5.         self.real = real
  6.         self.imag = imag
  7.  
  8.     def __add__(self, other):
  9.         klass = globals()[self.__class__.__name__]
  10.         result = klass()
  11.  
  12.         if isinstance(other, self.__class__):
  13.             result.set_real(self.get_real() + other.get_real())
  14.             result.set_imag(self.get_imag() + other.get_imag())
  15.         else:
  16.             result.set_real(self.get_real() + other)
  17.             result.set_imag(self.get_imag())
  18.  
  19.         return result
  20.  
  21.     def __radd__(self, other):
  22.         klass = globals()[self.__class__.__name__]
  23.         result = klass()
  24.  
  25.         result.set_real(self.get_real() + other)
  26.         result.set_imag(self.get_imag())
  27.  
  28.         return result
  29.  
  30.     def __str__(self):
  31.         real_str = str(self.real)
  32.         imag_str = '+' + str(self.imag) if self.imag > 0 else str(self.imag)
  33.         return real_str + imag_str + 'i'
  34.  
  35.     def get_real(self):
  36.         return self.real
  37.  
  38.     def get_imag(self):
  39.         return self.imag
  40.  
  41.     def set_real(self, real):
  42.         self.real = real
  43.  
  44.     def set_imag(self, imag):
  45.         self.imag = imag
  46.  
  47. if __name__ == '__main__':
  48.     a = MyComplex(3, 4)
  49.     b = MyComplex(4, 3)
  50.     print a + b
  51.     print a + 2
  52.     print 2 + a
  53.     print 3.2 + a
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement