【发布时间】:2019-10-11 23:57:07
【问题描述】:
我在 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)
不幸的是,我的方法不起作用。有什么建议吗?
【问题讨论】:
-
为什么不用Python内置的复杂类型呢?
-
@JohnO 因为我必须使用方法:)
-
观察 div-by-0
-
@Eve 你在计算结果的实部和虚部时犯了错误,它应该是
x = self.real * other.real - self.imag * other.imag和y = self.imag * other.real + self.real * other.imag
标签: python python-3.x class oop methods