[Tutor] design of Point class
Gregory, Matthew
matt.gregory at oregonstate.edu
Wed Aug 25 23:29:42 CEST 2010
Steven D'Aprano wrote:
> Other than using numpy, probably the simplest solution is to just
> subclass tuple and give it named properties and whatever other methods
> you want. Here's a simple version:
>
> class Point(tuple):
> [snip]
>
> What it doesn't give you (yet!) is:
>
> * distance between Points with different dimensions could easily be
> defined just by removing the len() comparison. zip() will
> automatically terminate at the shortest input, thus projecting the
> higher-dimension point down to the lower-dimension point;
> * other distance methods, such as Manhattan distance;
> * a nice exception when you as for (say) pt.z from a 2-D point, instead
> of raising IndexError;
> * point arithmetic (say, adding two points to get a third).
I hope you'll suffer me one more question on this thread. In thinking about creating other distance methods (as you suggest), how best to create a generic enough interface, so that ANY distance metric could be used. It seems like coding the Point class with multiple distance methods is not very flexible, especially if you wanted to iterate over those methods for any two points, e.g.
class Point(tuple):
def euclidean_distance(self, other):
...
def manhattan_distance(self, other):
...
def any_other_distance(self, other):
...
Would this be a place for a generic get_distance with a DistanceMetric subclass as a parameter, e.g.
class DistanceMetric(object):
def distance(self, p1, p2):
assert 0, 'Must be defined in subclasses'
class EuclideanDistMetric(DistanceMetric):
def distance(self, p1, p2):
...
class Point(tuple):
def get_distance(self, other, metric):
distance = metric.distance(self, other)
return distance
I'm sure I don't have all my syntax correct. Thanks for continued help.
matt
More information about the Tutor
mailing list