我正在尝试用
Python学习面向对象的编程.为此,我需要创建一个计算线的斜率的方法,该线将原点连接到一个点. (我认为)我们假设原点是(0,0).例如:
Point(4, 10).slopeFromOrigin()
2.5
Point(12, -3).slopeFromOrigin()
-0.25
Point(-6, 0).slopeFromOrigin()
0
我们使用方程slope =(Y2-Y1)/(X2-X1)来计算斜率.此外,由于不允许除以0,因此当方法失败时,我们需要返回None.这是我试过的:
class Point:
#Point class for representing and manipulating x,y coordinates
def __init__(self, initX, initY):
#Create a new point at the given coordinates
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
#define a method called slopeFromOrigin here
def slopeFromOrigin(self):
#set origin values for x and y (0,0)
self.x = 0
self.y = 0
#slope = (Y2 - Y1) / (X2 - X1)
if (Point(x) - self.x) == 0:
return None
else:
return (Point(y) - self.y) / (Point(x) - self.x)
#some tests to check our code
from test import testEqual
testEqual( Point(4, 10).slopeFromOrigin(), 2.5 )
testEqual( Point(5, 10).slopeFromOrigin(), 2 )
testEqual( Point(0, 10).slopeFromOrigin(), None )
testEqual( Point(20, 10).slopeFromOrigin(), 0.5 )
testEqual( Point(20, 20).slopeFromOrigin(), 1 )
testEqual( Point(4, -10).slopeFromOrigin(), -2.5 )
testEqual( Point(-4, -10).slopeFromOrigin(), 2.5 )
testEqual( Point(-6, 0).slopeFromOrigin(), 0 )
正如你所看到的,我试图说我们需要Point的第一个参数是x2,而Point的第二个参数是y2.我试过这种方式得到了
NameError:名称’y’未在第32行定义.
我也尝试得到Point的索引值,如下所示:
return(Point [0] – self.y /(Point [1] – self.x)
但这也给了我一个错误信息:
TypeError:’Point’不支持第32行的索引
我不确定如何从Point获取x和y参数的值,以便该方法在测试时有效.如果您有任何建议,请分享您的建议.谢谢.