"Gregory, Matthew" <matt.greg...@oregonstate.edu> wrote
I typically deal with geographic (either 2D or 3D) data, yet
there are occasions when I need n-dimensional points as well.
Thats OK.
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.
Thats OK too but adds some overhead.
Remember that inheritance should be based on behaviour not data
so determine the common methods of a Point. Write the ND version
of those methods.
Then create subclasses for 2D and 3D which convert the named args
to a list equivalent then call the superclass ND versions.
Every time you change the interface of inherited methods you
create for yourself extra work in converting types to match the
superclass. But that is often easier than rewriting the methods
from scratch.
Just remember that to get the best out of polymorphism - the primary
reason for inheritance - you should be able to mix n match instances
of
the subclasses with instances of the superclass - the Liskov
Substitution
Principle(LSP) - and if you break that you lose for yourself much of
the power of inheritance.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
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,
matt
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor