You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Point类的add、sub、mul方法返回Point对象而非字符串?

解决方法

问题出在你的__add__、__sub__、__mul__方法里,你返回的是格式化字符串而非新的Point对象,只要把这些方法改成返回新创建的Point实例就行,同时删掉方法里多余的print语句——因为__str__方法已经定义了打印格式,当你print一个Point对象时会自动调用它。

修改后的完整代码如下:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return_string = "Instance of Point\n\n"
        return_string += f"x: {self.x}\ny: {self.y}"
        return return_string

    def __add__(self, other):
        # 用计算后的坐标创建新Point实例并返回
        return Point(self.x + other.x, self.y + other.y)

    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)

    def __mul__(self, other):
        return Point(self.x * other.x, self.y * other.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y
    
    """ A simple representation of a point in 2d space"""


if __name__ == "__main__":
    point_one = Point(3,2)
    print(point_one)
    print()
    point_two = Point(5,3)
    print(point_two)
    print()
    point_three = point_one + point_two
    print(point_three)
    print()
    point_four = point_one - point_two
    print(point_four)
    print()
    point_five = point_one * point_two
    print(point_five)
    print()
    print(point_one == point_two) # prints False

关键修改说明

  • 运算方法不再返回字符串,而是用计算后的x、y值生成新的Point对象返回,这样后续你可以直接访问point_three.x这类属性,不会再出现str对象没有属性x的错误。
  • 移除了方法内的print("Instance of Point\n"),因为print新生成的Point对象时,会自动调用类的__str__方法,输出你预设的格式,和预期结果完全一致。

内容的提问来源于stack exchange,提问作者hal man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:20:40