Outlier_9 2022-06-04 20:10 采纳率: 100%
浏览 58
已结题

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日

悬赏问题

  • ¥30 数字信号处理实验报告
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程