如何为 python 中的复数构造 class?

how to construct a class for complex number in python?

首先,我知道scipy中有复数的数据结构。我只是在学习一本计算​​物理教科书,这是其中一个问题。 到目前为止,这是我得到的:

class complex:
    def __init__(self,x,y):
        self.re=x
        self.im=y
    def __add__(self, other):
        return complex(self.re+other.re, self.im+other.im)
    def __sub__(self, other):
        return complex(self.re-other.re, self.im-other.im)        
    def __mul__(self, other):
        return complex(self.re*other.re - self.im*other.im, 
        self.re*other.im + self.im*other.re)        
    def __repr__(self):
        return '(%f , %f)' %(self.re, self.im)

但是我应该如何在我创建的 class 中实现除法、复共轭、模数和相位?

谢谢

你应该用 __div__ 实现除法,用 __abs__ 实现模数。复杂的共轭和相位,您必须为其选择自己的方法名称。例如,

def conj(self):
    return complex(self.re, - self.im)

(用 z.conj() 调用)。请注意,您将无法为 class 定义新的 Python 语法:例如,您无法使 z* 工作。如果愿意,您还应该使用 __rmul____pow__ 定义右乘法。并且不要忘记一元减号 __neg__。但并非所有其他双下划线运算符方法都可以用复数实现。有 a list in the docs