Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Just for demo. DON'T DO THIS IN PRODUCTION CODE.
- class MyComplex(object):
- def __init__(self, real=0, imag=0):
- self.real = real
- self.imag = imag
- def __add__(self, other):
- klass = globals()[self.__class__.__name__]
- result = klass()
- if isinstance(other, self.__class__):
- result.set_real(self.get_real() + other.get_real())
- result.set_imag(self.get_imag() + other.get_imag())
- else:
- result.set_real(self.get_real() + other)
- result.set_imag(self.get_imag())
- return result
- def __radd__(self, other):
- klass = globals()[self.__class__.__name__]
- result = klass()
- result.set_real(self.get_real() + other)
- result.set_imag(self.get_imag())
- return result
- def __str__(self):
- real_str = str(self.real)
- imag_str = '+' + str(self.imag) if self.imag > 0 else str(self.imag)
- return real_str + imag_str + 'i'
- def get_real(self):
- return self.real
- def get_imag(self):
- return self.imag
- def set_real(self, real):
- self.real = real
- def set_imag(self, imag):
- self.imag = imag
- if __name__ == '__main__':
- a = MyComplex(3, 4)
- b = MyComplex(4, 3)
- print a + b
- print a + 2
- print 2 + a
- print 3.2 + a
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement