You need to enable JavaScript to run this app. 如何重载Python Point类加法运算符使其返回Line类实例
优惠活动
大模型
产品
解决方案
定价
更多

如何重载Python Point类加法运算符使其返回Line类实例

实现方案

要达成两个Point实例相加返回Line实例的需求,只需要补全Point类的__add__方法逻辑,同时修复测试代码的语法问题即可:

核心修改点

  • 补全Point类的__add__方法:直接以当前Point实例(加法左操作数)作为起点、传入的Point实例(加法右操作数)作为终点,实例化Line对象返回即可,可额外加类型校验避免非法调用。
  • 修复测试代码中print语句多写了一个左括号的语法错误。

完整可运行代码

import math
class Point:
    '''Class that creates points. Attributes: Eastings and Northings'''
    def __init__(self,x,y):
        self.eastings = x
        self.northings = y
    def getCoords(self):
        self.coords = (self.eastings,self.northings)
        return self.coords
    def setCoords(self,other_x,other_y):
        self.eastings = float(other_x)
        self.northings = float(other_y)
    def __str__(self):
        return f"{self.eastings},{self.northings}"
    def __add__(self,new_point):
        # 类型校验,仅支持和Point实例相加
        if not isinstance(new_point, Point):
            raise TypeError("加法右操作数必须为Point实例")
        # 返回Line实例
        return Line(start=self, end=new_point)


class Line:
    '''Class that creates line object based on two points'''
    def __init__(self,start,end):
        self.start = start #Type:Point (x1,y1)
        self.end = end #Type:Point (x2,y2)
        self.latitude = abs(self.end.eastings - self.start.eastings)
        self.departure = abs(self.end.northings - self.start.northings)
        self.distance = math.sqrt((self.latitude)**2 + (self.departure)**2)
        self.azimuth = math.degrees(math.atan2(self.departure,self.latitude))
    def __getitem__(self,key):
        if key == 0:
            ans = self.start
        elif key == 1:
            ans = self.end
        else:
            print("invalid index")
        return ans

#test code
a = Point(0,0)
b = Point(1,1)
c = Point(1,0.5)

line1 = a+b
print(type(line1))

运行结果

执行上述代码后输出为:

<class '__main__.Line'>

完全符合预期要求。

额外说明:原代码中Line类继承Point是不必要的,Line和Point没有"是一种"的继承关系,因此上面的代码里去掉了该继承逻辑,保留原继承也不影响功能运行。

内容的提问来源于stack exchange,提问作者rilke-nz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 08:24:06