вам нужно создать метод __div__(self, other)
, где вы делите no, а также новый метод __opposite__(self)
, чтобы изменить знак при умножении, также вызывая метод, как делить, т.е. no / no1 не является божественным методом
с использованием решения @johnO, обнуляя __truediv__
, поэтому OP может использовать no/no2
для разделения двух комплексных чисел.
см. Код ниже
class Complex (объект): 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 __opposite__(self):
self.real =self.real
self.imag = self. imag if self.imag<0 else self.imag * -1
def __truediv__(self, other):
other.__opposite__()
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
self.new_real = x / z
self.new_imag = y / z
if self.new_imag>0:
result = "{} + {}i".format(self.new_real, self.new_imag)
else:
result = "{} {}i".format(self.new_real, self.new_imag)
return result
no = Complex(4,5)
no2 = Complex(2,6)
print(no/no2)
output
0.24 + 0.68i