I am trying to learn object oriented programming in Python. To do this, I need to create a method that calculates the slope of the line connecting the origin to the point. (I think), we assume that the origin is (0,0). For instance:
Point(4, 10).slopeFromOrigin()
2.5
Point(12, -3).slopeFromOrigin()
-0.25
Point(-6, 0).slopeFromOrigin()
0
And we use the equation slope = (Y2 - Y1) / (X2 - X1)to calculate the slope. In addition, since division by 0 is not allowed, we need to return Nonewhen the method completed with an error. Here is what I tried:
class Point:
def __init__(self, initX, initY):
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
def slopeFromOrigin(self):
self.x = 0
self.y = 0
if (Point(x) - self.x) == 0:
return None
else:
return (Point(y) - self.y) / (Point(x) - self.x)
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 )
As you can see, I'm trying to say that we need the first Point parameter for x2, and the second Point parameter - y2. I tried it like this and got it
NameError: name 'y' is not defined on line 32.
I also tried to get the Point index values ββas follows:
return (Point[0] - self.y / (Point[1] - self.x)
But it also gave me an error message:
TypeError: 'Point' does not support indexing on line 32
, x y Point, , . , , . .