Point.py
import math
EPSILON=1e-20 # for testing equality of real numbers
class UnderDetermined(Exception):
"""
Raised in case of non-uniqueness of result
"""
pass
class Point:
"""
Encapsulates the essence of a point in 2D cartesian space
"""
def __init__(self, x=0, y=0):
"""
Point constructor.
Set x and y coordinates (both default to 0)
"""
self.set_x(x)
self.set_y(y)
def set_x(self, x=0):
"""
Set the private attribute x
"""
self.__x = x
def set_y(self, y=0):
"""
Set the private attribute y
"""
self.__y = y
def get_x(self):
"""
Get the private attribute x
"""
return self.__x
def get_y(self):
"""
Get the private attribute y
"""
return self.__y
def get_r(self):
"""
Get the polar coordinate radius
"""
x=self.get_x()
y=self.get_y()
return(math.sqrt(x*x+y*y))
def get_theta(self):
"""
Get the polar coordinate theta
"""
x=self.get_x()
y=self.get_y()
if math.fabs(x) < EPSILON:
if math.fabs(y) < EPSILON:
raise UnderDetermined, "infinitely many theta values possible"
elif y > 0:
theta = math.pi/2
else:
theta = -math.pi/2
else:
theta=math.atan(y/x)
return theta
def translate(self, delta_x, delta_y):
"""
Translate self over delta_x, delta_y
"""
self.set_x(self.get_x()+delta_x)
self.set_y(self.get_y()+delta_y)
def rotate(self, angle):
"""
Rotate self over angle
"""
r=self.get_r()
theta=self.get_theta()+angle
self.set_x(r*math.cos(theta))
self.set_y(r*math.sin(theta))
def __str__(self):
"""
String representation of self
"""
return("Point("+str(self.get_x())+","+str(self.get_y())+")")
def __eq__(self, other):
"""
Test for equality (==)
"""
diff_x = math.fabs(self.get_x() - other.get_x())
diff_y = math.fabs(self.get_y() - other.get_y())
if diff_x < EPSILON and diff_y < EPSILON:
return True
else:
return False
Generated by GNU enscript 1.6.1.