首页 > 解决方案 > 使用python对象和类查找点之间的距离

问题描述

我刚刚进入 Python 中的 OOP 并在课程中苦苦挣扎。基本上我正在创建一个需要找到两点之间的欧几里得距离的方法。我创建了一个创建两个点的方法,它可以工作。然后我创建了一个方法__sub__,用另一个点实例从这两个点中减去,然后分别对这两个点求平方。这也有效。

现在我需要创建一个方法point_distance,从这些点中获取结果__sub__并将这两个点相加,然后对总和执行平方根。我在底部包含了一些伪代码。我已经尝试了一些东西,但我认为我没有完全理解 OOP 的基础知识。任何帮助表示赞赏

class Point(object):
    """A 2D point in the cartesian plane"""
    def __init__(self, x, y):
        """
        Creates a point at the two co-ordinates

        Parameters:
            x (float): x coordinate in the 2D cartesian plane
            y (float): y coordinate in the 2D cartesian plane
        """

        self._x = x
        self._y = y


    def __sub__(self, other):
        """Return a new Point after subtracting this from 'other'
        Perform vector subtraction of the points, and then squares each of them respectively  
        point1 - point2 -> Point3 - Point4
        Parameters:
        other (Point): other point to be subtracted from this point.
        Return:
        Point: New point at position 'self' - 'other', then both squared
        """
        
        return Point((self._x - other.x())**2, (self._y - other.y())**2) 

    def x(self):
        """(float) Return the x coordinate of the point"""
        return self._x

    def y(self):
        """(float) Return the y coordinate of the point"""
        return self._y
    
    def __repr__(self):
        return 'Point({}, {})'.format(self._x, self._y)
   
    ##Problem in pseudocode below
  
    def point_distance(self, result from __sub__):
        add the two points together
        return the sqaure root of the sum of the two points obtained above

    

标签: pythonclassobjectoopinstance

解决方案


推荐阅读