[Tutor] design of Point class
Steven D'Aprano
steve at pearwood.info
Thu Aug 26 16:44:29 CEST 2010
On Thu, 26 Aug 2010 07:29:42 am Gregory, Matthew wrote:
> 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
That could work, but it seems like a terribly heavyweight solution for a
lightweight problem to me.
It doesn't save you any work -- you still have to code the distance
method, but instead of creating a single method, you have to create an
entire class. So it's more work.
I believe the simplest solution is to use the bound methods as first
class functions:
pt = Point(23, 42)
# choose a distance
if today == "Tuesday":
dist = pt.manhattan_distance
else:
dist = pt.euclidean_distance
for other in list_of_other_points:
print(dist(other))
--
Steven D'Aprano
More information about the Tutor
mailing list