【问题标题】:calculating distance between two points in python class计算python类中两点之间的距离
【发布时间】:2021-11-21 18:23:28
【问题描述】:

我正在尝试使用以下代码计算 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

【问题讨论】:

  • 请提供您期望的输入/输出示例
  • @azro 完成!我编辑了它

标签: python python-class


【解决方案1】:

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

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

__sub__ 用于覆盖Point 实例之间的减号- 运算符

【讨论】:

    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2010-10-30
      • 2011-04-23
      • 2014-11-14
      • 1970-01-01
      • 2017-08-27
      • 2015-08-16
      相关资源
      最近更新 更多