from cmath import exp class PolarComplex(object): def __init__(self, r, phi): self._r = r self._phi = phi def __repr__(self): return "{}({}, {})".format(PolarComplex.__name__, self._r, self._phi) def __abs__(self): return abs(self._r) def __mul__(self, other): if(isinstance(other, (int, float))): return PolarComplex(self._r * other, self._phi) if(isinstance(other, PolarComplex)): return PolarComplex(self._r * other._r, self._phi + other._phi) raise TypeError("*: cannot multiply {} and {}".format(type(other), type(self))) def __truediv__(self, other): if(isinstance(other, (int, float))): return PolarComplex(self._r / other, self._phi) if(isinstance(other, PolarComplex)): return PolarComplex(self._r / other._r, self._phi - other._phi) raise TypeError("/: cannot divide {} and {}".format(type(other), type(self))) def __str__(self): return str(self._r * exp(1j * self._phi)) def __rmul__(self): if(isinstance(other, (int, float))): return PolarComplex(self._r * other, self._phi) if(isinstance(other, PolarComplex)): return PolarComplex(self._r * other._r, self._phi + other._phi) raise TypeError("*: cannot multiply {} and {}".format(type(other), type(self))) def __rtruediv__(self, other): if(isinstance(other, (int, float))): return PolarComplex(other / self._r, -self._phi) if(isinstance(other, PolarComplex)): return PolarComplex(other._r / self._r, other._phi - self._phi) raise TypeError("/: cannot divide {} and {}".format(type(other), type(self))) if( __name__ == "__main__"): c = PolarComplex(3, 0.3) print(repr(c)) print(str(c)) print(repr(c / 3)) print(repr(c * 3)) z = PolarComplex(2, 0.2) print(repr(c * z)) print(repr(c / z))