python - Python 3 类中的复数除法

标签 python python-3.x class oop methods

我在 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

关于python - Python 3 类中的复数除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56308592/

相关文章:

python - 为什么使用cv2.calcHist总是出现错误 "returned NULL without setting an error"

python - 需要在列表中查找字符数超过一定数量的字符串

javascript - React 中的 throttle

python - python 3中类 'bytes'的不同表示

python - 如何在 Python3.x 中检索单个 7zip 文件而不解压所有文件?

python - buildbot:使用 SSL 连接到 IRC 服务器

python - 根据 Pandas 中另一列中值的间隔选择列中值的范围

python - 如何将二维列表转换为集合?

python - `context` 中的 `multiprocessing.pool.Pool` 参数是什么意思?

python - 有没有办法将装饰器应用于需要类信息的 Python 方法?