问题遇到的现象和发生背景
用Python类的方法实现复数四则运算
问题相关代码,请勿粘贴截图
class Complex:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Complex(self.x + other.x, self.y + other.y)
def __sub__(self, other):
return Complex(self.x - other.x, self.y - other.y)
def __mul__(self, other):
return Complex(self.x * other.x - self.y * other.y, other.x * self.y + self.x * other.y)
def __truediv__(self, other):
return Complex((self.x * other.x + self.y * other.y) / (other.x * other.x + other.y * other.y),
(other.x * self.y - self.x * other.y) / (other.x * other.x + other.y * other.y)
def __str__(self):
return "%d + %di" % (self.x, self.y)
c1 = Complex(2, 4)
c2 = Complex(3, 1)
c3 = c1 + c2
c4 = c1 - c2
c5 = c1 * c2
c6 = c1 / c2
print(c3)
print(c4)
print(c5)
print(c6)
运行结果及报错内容
File "C:/Users/hp/PycharmProjects/lesson/practice.py", line 139
def __str__(self):
^
SyntaxError: invalid syntax
我的解答思路和尝试过的方法
之前编辑的确实是少了括号,改过后这里却还有问题
我想要达到的结果
可以解释一下吗谢谢