Calculating Euclidean distance using Magic Methods in Python 3

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

    As has been mentioned, it may not be a good idea to use a Point class to represent vectors. It's ok in simple programs, but it can get confusing in more complex code. The usual practice is to make points immutable. But anyway...

    To do this Euclidean distance operation we can "abuse" the new __matmul__ magic method. This method is invoked by the @ operator. Here's a short demo based on your code. Notice that I'm using x and y as the attributes, there's no good reason to mark them as private.

    class Point:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def __repr__(self):
            return "Point({}, {})".format(self.x, self.y)
    
        def __add__ (self, other ):
            return Point(self.x + other.x, self.y + other.y)
    
        def __sub__ (self, other ):
            return Point(self.x - other.x, self.y - other.y)
    
        def __pow__(self, p):
            return Point(self.x ** p, self.y **p)
    
        def __abs__(self):
            d = self ** 2
            return (d.x + d.y) ** 0.5
    
        def __matmul__(self, other):
            ''' Euclidean distance between self & other '''
            return abs(self - other)
    
    # Test
    
    a = Point(5, 6)
    b = Point(2, 2)
    print(a + b)
    print(a - b)
    print(a @ b)
    

    output

    Point(7, 8)
    Point(3, 4)
    5.0
    

提交回复
热议问题