Home > database >  Finding distance between two points in OOP
Finding distance between two points in OOP

Time:01-20

The program creates a class for points and has three functions: one that shows the coordinates of the point, another that moves the coordinates, and the last one that calculates the distance between them. I'm stuck with the last one I don't know how to do that.

from math import sqrt


class Points:
    def __init__(self, x1, y1):
        self.x1 = x1
        self.y1 = y1

    def show(self):
        return (self.x1, self.y1)

    def move(self, x2, y2):
        self.x1  = x2
        self.y1  = y2

    def dist(self, point):
        return sqrt(((point[0] - self.x1) ** 2)   ((point[1] - self.y1) ** 2))


p1 = Points(2, 3)
p2 = Points(3, 3)
print(p1.show())

print(p2.show())

p1.move(10, -10)
print(p1.show())

print(p2.show())

print(p1.dist(p2))

CodePudding user response:

Access point members in dist like this:

return sqrt(((point.x1 - self.x1) ** 2)   ((point.y1 - self.y1) ** 2))

CodePudding user response:

What you did wrong was that you were trying to index a class. Try the following solution (I made it simpler):

def dist(self, point):
    plusx = self.x1 - point.x1
    plusy = self.y1 - point.y1
    
    pythagoras = sqrt((plusx**2) (plusy**2))
    return pythagoras

#output after the other code: 13.45362404707371
  • Related