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