I have a code that calculates Euclidean distance for me:
class Point:
\"\"\"A point in two-dimensional space.\"\"\"
def __init__(self, x, y):
se
It does not make sense for the difference of two points to be a point. It seems the object you are trying to implement is in fact a vector.
Then the distance corresponds to the norm of a vector, implemented with __abs__
.
class Vector:
def __init__(self, *args):
self._coords = args
def __add__(self, other):
return Vector(*[x + y for x, y in zip(self._coords, other._coords)])
def __sub__(self, other):
return Vector(*[x - y for x, y in zip(self._coords, other._coords)])
def __abs__(self):
"""Euclidian norm of the vector"""
return sum(x**2 for x in self._coords) ** (1 / 2)
v1 = Vector(1, 3)
v2 = Vector(4, -1)
print(abs(v2 - v1)) # 5.0
# Also works in higher dimensions
v3 = Vector(1, -1, 0)
v4 = Vector(4, 6, -2)
print(abs(v3 - v4)) # 7.87