Skip to main content
 首页 » 编程设计

python之Python 3 类中的复数除法

2025年05月04日16jirigala

我在 Python 类中为应该除以两个复数的复数创建 __div__ 方法时遇到问题。

这是我的代码:

class Complex(object): 
        def __init__(self, real = 0, imag = 0): 
            self.real = real 
            self.imag = imag 
 
        def __str__(self): 
            if self.imag > 0: 
                return str(self.real) + "+" + str(self.imag) + "i" 
            elif self.imag < 0: 
                return str(self.real) + str(self.imag) + "i" 
 
        def __div__(self, other): 
            x = self.real * other.real + self.imag * other.imag 
            y = self.imag * other.real - self.real * other.imag 
            z = other.real**2 + other.imag**2 
            real = x / z 
            imag = y / z 
            return Complex(real, imag) 
 
no = Complex(2,-8) 
no2 = Complex(3,7) 
print(no/no2) 

不幸的是,我的方法行不通。有什么建议吗?

请您参考如下方法:

__div__ 在 Python 3 中不再存在。它被替换为 __truediv__ for/和 __floordiv__ for//

看看 https://docs.python.org/3/reference/datamodel.html