12 Aralık 2017

Python Operator Overloading

class Complex:
'this class simulates complex numbers'
def __init__(self, real = 0, imag = 0):
if type(real) not in (float,int) or type(imag) not in (int,float):
raise Exception("Args are not numbers")
self.real = real
self.imag = imag

def GetReal(self):
return self.real

def GetImag(self):
return self.imag

def SetReal(self,val):
self.real = val

def SetImag(self,val):
self.imag = val

def __str__(self):
return str(self.GetReal()) + ' + ' + str(self.GetImag()) + 'i';

def __add__(self,other):
return Complex(self.GetReal()+other.GetReal(),self.GetImag()+other.GetImag())

def __mul__(self,other):
if(type(other) in (float,int)):
return Complex(self.GetReal()*other,self.GetImag()*other)
else:
return Complex(self.GetReal()*other.GetReal() - self.GetImag()*other.GetImag(), self.GetReal()*other.GetImag() + other.GetReal()*self.GetImag())

def __truediv__(self,other):
if type(other) in (int, float):
return Complex(self.GetReal()/float(other), self.GetImag()/float(other))
else:
a = Complex(other.GetReal() , -1 * other.GetImag())
self = a * self
m = a * other
return self / m.GetReal()




a = Complex(2, -2)
b = Complex(-1, 1)