Making a Point Class in Python
Making a Point Class in Python
Dont forget math.hypot
def distance(self, p):
dx = self.X - p.X
dy = self.Y - p.Y
return hypot(dx, dy)
-
You declared
distance
as taking an argumentp
; inside the method youre referring to it asother
. Changep
toother
in the declaration so they match. -
sqrt()
isnt a builtin; you need to doimport math
and refer to it asmath.sqrt()
. -
You arent doing anything with the
testPoint()
function you declare; you can invoke it by adding a line at the end like:
print distance = %s%(testPoint())
At that point, your code works and computes a distance of 4.0 between your points.
Now, some style issues:
-
In Python, you dont generally privatize member variables, and you dont bother writing trivial getters and setters, so you can remove the
getX()
andgetY()
methods and just refer top.X
andp.Y
directly given aPoint p
. -
The
math
module has a convenient hypotenuse function, so indistance()
you can change the return line toreturn math.hypot(dx,dy)
. -
By default, a user defined object has an unattractive string representation:
<__main__.Point object at 0x1004e4550>
You should define a string conversion method in your class like so:
def __str__(self):
return Point(%s,%s)%(self.X,self.Y)
This will be used when the object is printed, or otherwise needs to be converted to a string.
Making a Point Class in Python
In your Point.distance method, you reference other.X and other.Y; Other does not exists.
You should either change the distance signature to be distance(self, other) or change the code to use p.
You will also need to import math.sqrt:
from math import sqrt