革斤要加油 2022-06-04 20:10 采纳率: 100%
浏览 55
已结题

Python类的方法实现复数四则运算

问题遇到的现象和发生背景

用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


我的解答思路和尝试过的方法

之前编辑的确实是少了括号,改过后这里却还有问题

我想要达到的结果

可以解释一下吗谢谢

  • 写回答

1条回答 默认 最新

  • 请叫我问哥 Python领域新星创作者 2022-06-04 20:32
    关注

    最后一个函数的括号缺失,试试这样:

        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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

    报告相同问题?

    问题事件

    • 系统已结题 6月12日
    • 已采纳回答 6月4日
    • 修改了问题 6月4日
    • 创建了问题 6月4日

    悬赏问题

    • ¥50 74LS系列 74LS00 74LS04设计一个RS485电路(关键词-差分)
    • ¥30 各位help写一下代码
    • ¥15 在运行SDEdit模型下载不了
    • ¥15 求51控制l298n驱动的小车中超声波避障怎么写
    • ¥15 电脑连上WIFI却用不了
    • ¥30 MATLAB在RLC电路的固有响应和阶跃响应GUI仿真报告
    • ¥15 hyper-v出现的问题
    • ¥15 有能用的可加酬金,求可以批量下载懒人听书的软件,能登录自己帐号的。
    • ¥100 高博一起做RGB-D SLAM(5)VO无法出visualisation问题
    • ¥15 使用matlab进行手眼标定的仿真验证,得到齐次矩阵与opencv相差较大