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

Python自定义Point类计算两点距离出现__sub__未定义错误如何解决

错误原因

  • __sub__是类的实例方法,不能直接调用,需要通过实例对象触发,比如直接写self - other就会自动调用__sub__方法
  • 原distance方法内的计算逻辑错误,错误构造了新的Point对象传参,减法应该是当前实例的x/y属性减去另一个实例的对应属性
  • math.sqrt()仅接收1个数值参数,原代码传入了p1和p2两个参数,不符合函数要求
  • 你提到的公式实际是欧氏距离的计算逻辑:√[(x1-x2)² + (y1-y2)²],如果只需要距离平方可以省略开根号步骤

修正后完整代码

import math
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return "Point({0}, {1})".format(self.x, self.y)
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)
    
    def distance(self, other):
        # 两个点相减得到坐标差的Point对象
        diff = self - other
        # 计算平方和再开根号
        return math.sqrt(diff.x ** 2 + diff.y ** 2)


def dist_result(points):
    points = [Point(*point) for point in points]
    return [points[0].distance(point) for point in points]

测试示例

# 测试:计算(0,0)到(3,4)的距离,预期结果为5.0
print(dist_result([(0,0), (3,4)]))
# 输出:[0.0, 5.0]

内容的提问来源于stack exchange,提问作者Seif Mahdi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:57:03