# ShowBetterPoint.py """ Shows (in part) what "good design" means when organizing a class. """ from math import sqrt class Point: """ Attributes: x: float, the x-coordinate of a point y: float, the y-coordinate of a point d: float, the distance of the point to the origin """ def __init__(self,x,y): """ Creates a Point object PreC: x and y are numbers """ assert type(x)==float or type(x)==int,'x must be a number' assert type(y)==float or type(y)==int,'y must be a number' x = float(x) y = float(y) self.x = x self.y = y self.d = sqrt(x**2+y**2) def __str__(self): """ pretyy prints self. """ return '(%6.3f,%6.3f) distance = %6.3f'%(self.x,self.y,self.d) def get_x(self): return self.x def get_y(self): return self.y def get_d(self): return self.d def set_x(self,x): assert type(x)==float or type(x)==int,'x must be a number' self.x = x self.d = sqrt(self.x**2+self.y**2) def set_y(self,y): assert type(y)==float or type(y)==int,'y must be a number' self.y = y self.d = sqrt(self.x**2+self.y**2) def Dist(self,P): """ Returns the distance from self to P PreC: P is a point """ assert isinstance(P,Point),'P must be a Point' return sqrt((self.x-P.x)**2+(self.y-P.y)**2) def Midpoint(self,P): """ Returns the midpoint of the line segment that connects self and P. PreC: P is a point """ assert isinstance(P,Point),'P must be a Point' xm = (self.x+P.x)/2.0 ym = (self.y+P.y)/2.0 return Point(xm,ym)