我必须首先创建一个名为 point 的类,将 x 和 y 作为参数来找到斜率。然后我必须创建一个名为 line 的类,它以两个点作为参数。在线类中,我必须创建一个名为 get slope 的函数来计算斜率并将其返回。这是我想出的
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
class Line:
def __init__(self,p1,p2):
self.p1 = (x1,y1)
self.p2 = (x2,y2)
def getSlope(self):
xvalues = (self.p2.x - self.p1.x)
yvalues = (self.p2.y - self.p1.y)
slope = yvalues/xvalues
return slope
我无法让它工作
请您参考如下方法:
你犯了一些错误,首先在 python(版本低于 3)中除法返回整数而不是 float 。你应该从 future 包中导入除法,其次你没有遵循 python 中的缩进约定。以下是测试和工作的代码。
from __future__ import division
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
class Line:
def __init__(self,p1,p2):
self.p1 = p1
self.p2 = p2
def getSlope(self):
xvalues = (self.p2.x - self.p1.x)
yvalues = (self.p2.y - self.p1.y)
print self.p1.x
slope = yvalues/xvalues
return slope
p = Point(1,0);
p2 = Point(5,3);
l = Line(p,p2);
print(l.getSlope());
