Python 运算符重载

【Python 运算符重载】Python 运算符重载

class MyComplex: def __init__(self, _real, _imag): self.real = _real self.imag = _imag def __add__(self, comp): if type(self) is type(comp): return MyComplex(self.real+comp.real, self.imag+comp.imag) else: return MyComplex(self.real+comp, self.imag) def __sub__(self, comp): if type(self) is type(comp): return MyComplex(self.real-comp.real, self.imag-comp.imag) else: return MyComplex(self.real-comp, self.imag) def __mul__(self, comp): if type(self) is type(comp): return MyComplex(self.real*comp.real-self.imag*comp.imag, self.real*comp.imag+self.imag*comp.real) else: return MyComplex(self.real*comp, self.imag*comp) def __str__(self): if self.imag>=0: return f'{self.real}+{self.imag}i' else: return f'{self.real}{self.imag}i'def main(): c1 = MyComplex(3,-5) c2 = MyComplex(2,3) print(c1,c2) print('c1+c2=', c1+c2) print('c1-c2=', c1-c2) print('c1*c2=', c1*c2) if __name__=="__main__": main()

    推荐阅读