[Tutor] design of Point class

Gregory, Matthew matt.gregory at oregonstate.edu
Fri Aug 20 17:45:18 CEST 2010

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
2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 5.0)'
   rather than passing in a list

Or am I totally off on thinking this is a good place for inheritance?

Thanks for any help,

More information about the Tutor mailing list