Calculating Euclidean distance using Magic Methods in Python 3

后端 未结 4 512
广开言路
广开言路 2021-01-23 14:46

I have a code that calculates Euclidean distance for me:

class Point:
    \"\"\"A point in two-dimensional space.\"\"\"

    def __init__(self, x, y):
        se         


        
4条回答
  •  太阳男子
    2021-01-23 15:14

    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)
    

    Example

    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
    

提交回复
热议问题