python - 使用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
解决方案
推荐阅读
- vb.net - RDLC 报告数据集/表和自定义代码
- html - 如何使用 SSH 重命名子目录中的所有文件
- python - 如何在python中自动打开电子邮件并单击带有selenium的链接
- javascript - 显示何时在数组中找到元素
- google-oauth - Google oauth 响应 redirect_uri_mismatch 错误
- php - Laravel 5.7 身份验证 + 反应。如何将它们结合起来?
- c - 为什么没有使用 double 函数中声明的数字?(C)
- regex - Oracle 正则表达式和替换
- swift - Swift 等待异步请求完成
- r - 在R中从文本字符串转换为日期