import math
class point:
def __init__(self,p1,p2):
self.p1 = p1
self.p2 = p2
def distancepoint(self):
x1,y1 = self.p1
x2,y2 = self.p2
distance = math.sqrt((x1-x2)**2 + (y1-y2)**2)
return distance
p1 = point(2,4)
p2 = point(1,6)
distance = distancepoint(p1,p2)
print (f'Distance between 2 points: {distance}')
我是Python初学者。我不知道如何解决这个问题。
您似乎对变量感到困惑:在点类定义中,p1和p2是点坐标,distancepoint是类方法,而后来的p1和p2是点,并且您尝试使用distancepoint作为函数(外部一类);这就是您可能想做的事情:
import math
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def distancepoint(self, other):
distance = math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
return distance
p1 = point(2,4)
p2 = point(1,6)
distance = p1.distancepoint(p2)
print (f'Distance between 2 points: {distance}')
# Distance between 2 points: 2.23606797749979
通过查看代码,您似乎正在尝试编写一个程序来获取两点之间的距离,如果我是正确的,请尝试此代码。
您的代码实际上调用了一个类方法,并且您在没有不可调用的对象的情况下调用它。
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_to(self, other_point):
return math.sqrt((self.x - other_point.x)**2 + (self.y - other_point.y)**2)
p1 = Point(2, 4)
p2 = Point(1, 6)
distance = p1.distance_to(p2)
print(f'Distance between 2 points: {distance}')