[Tutor] design of Point class

Alex Hall mehgcap at gmail.com
Fri Aug 20 17:54:19 CEST 2010


On 8/20/10, Gregory, Matthew <matt.gregory at oregonstate.edu> wrote:
> Hi all,
>
> I often struggle with object design and inheritance.  I'd like opinions on
> how best to design a Point class to be used in multiple circumstances.
>
> I typically deal with geographic (either 2D or 3D) data, yet there are
> occasions when I need n-dimensional points as well.  My thought was to
> create a superclass which was an n-dimensional point and then subclass that
> to 2- and 3-dimensional cases.  The rub to this is that in the n-dimensional
> case, it probably makes most sense to store the actual coordinates as a list
> whereas with the 2- and 3-D cases, I would want 'named' variables, such as
> x, y, z.
>
> Here's a (very rough) first cut at the constructor and a generic distance
> function for the n-dimensional case:
>
> class PointND(object):
>     def __init__(self, a_list):
>         self.a_list = a_list[:]
>
>     def distance(self, right):
>         assert(len(self.coord) == len(right))
>         squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)]
>         return math.sqrt(sum(squared_diffs))
>
> But how can I subclass this in such a way to be able to:
>
> 1) Have named variables in the 2- and 3-D cases
I assume you will have separate subclasses for both 2d and 3d, so just
set up each subclass's __init__ to accept the proper amount and order
of arguments.
> 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0,
> 5.0)'
>    rather than passing in a list
class 2dPoint(point):
  def __init__(self, x, y):
    self.x=x
    self.y=y
    self.points=[x,y]

>
> Or am I totally off on thinking this is a good place for inheritance?
I would use subclassing. Designed right, this gives you access to
common functions like distance but also lets you customize each
subclass with specific methods unique to that subclass. Just my 2
cents, though, and I am not too experienced here.
>
> Thanks for any help,
> matt
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list