function "overloading"

Alex Martelli Alex.Martelli at think3.com
Fri Jan 21 11:32:15 EST 2000


Janos Blazi writes:

: I have 3 classes called Tline, Tsegment and Tpoint, repectively. I'd like
to
: write a function "subset" that cheks if one of the instances of the above
: classes  is a subset of another instance (as long as this is sensible).
:
: I am afraid I cannot overload the name "subset" and additionally when
subset
: has control it cannot decide the type of its arguments: Does this mean I
: have to write several *different* subset functions having different names

The built-in isinstance() function will let you check whether an object is
an instance of a given class (or, a given type-object).  You could use
that, plus, ideally, some polymorphism in your above-mentioned classes, 
to get exactly what you want, it seems to me.

I.e., suppose you have:

class Tpoint:
	def liesAlongLine(self,line):
		# gives desired boolean result if line is a Tline
	def liesOnSegment(self,segm):
		# gives desired boolean result if segm is a Tsegment

class Tsegment:
	def oneExtreme(self):
		# returns a Tpoint that's one extreme of the segment
	def otherExtreme(self):
		# guess what it returns
	def hasPoint(self,point):
		return point.liesOnSegment(self)
	def containsSegment(self,otherSegment):
		return self.hasPoint(otherSegment.oneExtreme()) and
self.hasPoint(otherSegment.otherExtreme())

class Tline:
	def hasPoint(self,point):
		return point.liesAlongLine(self)
	def containsSegment(self,aSegment):
		return self.hasPoint(aSegment.oneExtreme()) and
self.hasPoint(aSegment.otherExtreme())


def subset(haystack,needle):
	if isinstance(needle,Tpoint):
		return haystack.hasPoint(needle)
	elif isinstance(needle,Tsegment):
		return haystack.containsSegment(needle)


Basically, you need to double-dispatch on the types of both haystack and
needle, and this approach is based on a type-test for needle plus some
polymorphism in the haystack.  Other approaches would clearly also be
possible; in particular, I have recently seen on this list (==newsgroup)
an announcement of a general purpose multiple-dispatch package -- I
have not looked at it further, but that might certainly be a way to solve
your
problem, for example.

A "trick" solution to this particular case might come from considering a
point equivalent to a segment where both extremes coincide (==return
the same point...), of course.  But this a pretty specific case:-).


Alex





More information about the Python-list mailing list