Python类设计

时间:2012-04-16 02:37:20

标签: python class

需要一些帮助。

我目前的代码框架如下所示:

import math
epsilon = 0.000001

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

需要添加一个名为dist_to_point的方法,该方法将另一个点对象p作为参数并返回两点之间的欧氏距离。我可以使用math.sqrt。

测试用例:

abc = Point(1,2)
def = Point(3,4)
abc.dist_to_point(def) ===> 2.8284271

我该怎么做?非常困惑。感谢。

编辑:不是作业。我理解添加方法但我不知道如何进行欧氏距离计算以及self._x等。我在那里感到困惑

2 个答案:

答案 0 :(得分:2)

您需要添加一个带有签名dist_to_point(self, p)的方法。在该方法中,您需要实现两空间中两点之间距离的公式(可从维基百科和其他来源获得)。

在您的方法中,您可以将名为的点的坐标称为self._xself._y参数点的坐标为p._xp._y

这足以让你入门吗?

答案 1 :(得分:0)

如果你说这不是作业,那么就需要直接回答。这是一些有效的代码:

import math
epsilon = 0.000001

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y
    def dist_to_point(self, other):
        'Compute the Euclidean distance between two Point objects'
        delta_x = self._x - other._x
        delta_y = self._y - other._y
        return (delta_x ** 2 + delta_y ** 2) ** 0.5

示例会话:

>>> point_abc = Point(1,2)
>>> point_def = Point(3,4)
>>> point_abc.dist_to_point(point_def)
2.8284271247461903