[英]Finding distance between two points in OOP
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.程序为点创建了一个class,有三个函数:一个显示点的坐标,一个移动坐标,最后一个计算它们之间的距离。 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))
Access point
members in dist
like this:像这样在
dist
中访问point
成员:
return sqrt(((point.x1 - self.x1) ** 2) + ((point.y1 - self.y1) ** 2))
What you did wrong was that you were trying to index a class. Try the following solution (I made it simpler):您做错的是您试图索引 class。请尝试以下解决方案(我使其更简单):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.