On 8/20/2010 11:45 AM, Gregory, Matthew 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
2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 
5.0)' rather than passing in a list

One class fits all:

class PointND(list):
    def __init__(self, *a_list):
        super(PointND, self).__init__(a_list)
        if len(self)<= 2:
            self.x = self[0]
        if len(self) == 2:
            self.y = self[1]


--
Bob Gailer
919-636-4239
Chapel Hill NC

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to