[Tutor] line class
Alan Gauld
alan.gauld at btinternet.com
Tue Jul 8 18:03:42 CEST 2008
"Christopher Spears" <cspears2002 at yahoo.com> wrote
> class Point(object):
> def __init__(self, x=0.0,y=0.0):
> self.x = float(x)
> self.y = float(y)
>
> def __repr__(self):
> coord = (self.x,self.y)
> return coord
You could add a couple of methods here to get deltaX and
deltaY values Or even define __sub__ to return a tuple
This would save you pokintg about inside the Point objects
in line which is a design anti-pattern in OOP terms.
> class Line(object):
> def length(self):
> dist_x = abs(self.p2.x - self.p1.x)
> dist_y = abs(self.p2.y - self.p1.y)
You don;t bneed the abs() since when you square them
you will always get a positive number.
> dist_x_squared = dist_x ** 2
> dist_y_squared = dist_y ** 2
> line_length = math.sqrt(dist_x_squared + dist_y_squared)
> return line_length
With __sub__ defined you could write:
def length(self):
dx,dy = self.p1 - self.p2
return (dx**2 + dy **2) ** 0.5
Let objects do it to themselves - the law of demeter.
> def slope(self):
> dist_y = self.p2.y - self.p1.y
> dist_x = self.p2.x - self.p1.x
> line_slope = dist_y/dist_x
> return line_slope
And this becomes
def slope(self):
dx,dy = self.p1 - self.p2
return dy/dx
Just a thought. Get the objects to do the work not
the using methods
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list