Source code for Point2d

""" Class example for storing 2d objects, with x and y
    as member values.
    
"""


import math

class Point2d(object):
[docs] def __init__ (self, x, y): """Create a new point object given x,y values. """ self.x = x self.y = y self.d = math.sqrt(self.x**2+self.y**2)
[docs] def move_left(self, disp): """Example of a function that changes the object, but does not return anything. """ self.x -= disp
[docs] def move_right(self, disp): """Example of a function that changes the object, but does not return anything. """ self.x += disp
[docs] def move_up(self, disp): """Example of a function that changes the object, but does not return anything. """ self.y += disp
[docs] def move_down(self, disp): """Example of a function that changes the object, but does not return anything. """ self.y -= disp
[docs] def __str__(self): """Example of a function that does not change the object, but returns something, a string representation of the object:: print p1 print str(p1) """ return str(self.x) + "," + str(self.y)
[docs] def __add__(self, other): """Adds two points and return the resulting point. Can call as:: p1.__add__(p2) p1 + p2 """ newp = Point2d(self.x, self.y) newp.x += other.x newp.y += other.y return newp
[docs] def __sub__(self, other): """Subtracts one point from another and returns the resulting point. Can call as:: p1.__sub__(p2) p1 - p2 """ newp = Point2d(self.x, self.y) newp.x -= other.x newp.y -= other.y return newp
[docs] def dist(self, other): """Returns the Euclidian distance between two points. """ d = math.sqrt( (self.x-other.x)**2 + \ (self.y-other.y)**2 ) return d
[docs] def manhattan(self, other): """Returns the Manhattan distance between two points. """ d = abs(self.x-other.x) + abs(self.y-other.y) return d
[docs] def haversine(self, other): """Returns the Haversine distance in miles between two points representing latitude for x and longitude for y. See also http://en.wikipedia.org/wiki/Haversine_formula """ lat1 = self.x * (math.pi / 180.0) long1 = self.y * (math.pi / 180.0) lat2 = other.x * (math.pi / 180.0) long2 = other.y * (math.pi / 180.0) dlat = (lat1-lat2) dlong = (long1-long2) a = math.sin(dlat/2)**2 + \ math.cos(lat1) * math.cos(lat2) * math.sin(dlong/2)**2 c = 2*math.atan2( math.sqrt(a), math.sqrt(1-a) ) R = 6371 / 1.609 return R*c
if __name__ == "__main__": ##Test code for the Point2d class p1 = Point2d(10,20) p2 = Point2d(30,40) print "p1:", p1 print "p2:", p2 p1.move_left(5) print "p1 after moving left by 5:", p1 print "p1+p2:", p1+p2 print "p1-p2:", p1-p2 print "Euclidian distance", p1.dist(p2) print "Manhattan distance", p1.manhattan(p2)