Calculating Euclidean distance using Magic Methods in Python 3

后端 未结 4 549
广开言路
广开言路 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:22

    Note that your definition of __pow__ is a bit nonstandard for vectors.

    But as it is, the distance of two points p1 and p2 could be written as sum((p1 - p2)**2)**.5. So we need your __pow__ method, your __sub__ method, and the only other addition is an __iter__ method which allows sum to work:

    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 __sub__(self, other):
            return Point(self._x - other._x, self._y - other._y)
    
        def __pow__(self, power):
            return Point(self._x**power, self._y**power)
    
        def __iter__(self):
            yield self._x
            yield self._y
    
        def distance(self, other):
            return sum((self - other)**2)**.5
    
    p1 = Point(2, 3)
    p2 = Point(5, -1)
    
    print(p1.distance(p2))
    Out: 5.0
    

    That's the shortest way based on your existing code anyway. You could experiment further by adding a scalar multiplication method and an addition method and then defining sub as p1 + (-1)*p2. You can also make things a bit easier on yourself by implementing a __repr__ method.

提交回复
热议问题