我有一个为我计算欧几里德距离的代码:
class Point:
"""A point in two-dimensional space."""
def __init__(self, x, y):
self._x = x
self._y = y
def __eq__(self, other):
return self._x == other._x and self._y == other._y
def distance(self, other):
new_x = self._x - other._x
new_y = self._y - other._y
print(new_x,' ',new_y)
return (new_x ** 2 + new_y ** 2) ** 0.5
p1 = Point(10, 4)
p2 = Point(3, 1)
print('Euclidean distance : 'p1.distance(p2))
但是,现在我想使用 python 中的魔术方法来计算这个距离,比如__sub__
and __pow__
。我已经成功实施__sub__
但我不知道如何实施__pow__
和平方根。到目前为止,这是我的代码:
class Point_1(object):
def __init__(self, x, y):
self._x = x
self._y = y
def setX(self, x,y):
self._x = x
self._y = y
def getX(self):
return self._x,self._y
def __sub__ (self, other ):
return Point_1(self._x - other._x, self._y - other._y)
def __pow__(self,p):
return Point_1(self._x ** p, self._y **p)
p1 = Point_1(10,4)
print(p1.getX())
p2 = Point_1(3,1)
print(p2.getX())
p3 = p1 - p2
我如何使用魔术方法来实现公式的其余部分。我真的很困惑。我将不胜感激。