计算 python class 中两点之间的距离

calculating distance between two points in python class

我正在尝试使用以下代码计算 python 中两点之间的距离:

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) #<-- MODIFIED THIS
    
    def distance(self, other):
        p1 = __sub__(Point(self.x , other.x))**2
        p2 = __sub__(Point(self.y,other.y))**2
        p = math.sqrt(p1,p2)
        return p


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

但它正在返回:

NameError: name '__sub__' is not defined

你能告诉我如何正确编写该函数吗?

所以我期待输入:

1=(1,1)  and  2=(2,2) 

我想使用以下方法计算距离:

=|2−1|=(1−2)^2+(1−2)^2

__sub__是实例方法,不是全局函数。调用实例方法的一般方式是作为实例的属性,例如:

difference = p1.__sub__(p2)

相当于:

difference = Point.__sub__(p1, p2)

由于__sub__是一个魔术方法,您也可以通过减法运算符调用它:

difference = p1 - p2

要根据您的 __sub__ 方法实施您的 distance 方法,我认为您需要以下内容:

    def distance(self, other):
        diff = self - other
        return math.sqrt(diff.x ** 2 + diff.y ** 2)

您唯一需要的公式是Pythagore,您不需要创建一些临时点,只需执行:

def distance(self, other):
    dx = (self.x - other.x) ** 2
    dy = (self.y - other.y) ** 2
    return math.sqrt(dx + dy)

__sub__ 是覆盖 - 运算符,在 Point 个实例之间