Adding an interface to existing classes

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Dec 25 08:27:49 EST 2011


On Sun, 25 Dec 2011 23:32:41 +1100, Chris Angelico wrote:

> On Sun, Dec 25, 2011 at 11:10 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> class Point:  # An abstract class.
>>    def intersect(self, other):
>>        blah; blah; blah
>>        return Point(x, y)  # No, wrong, bad!!! Don't do this.
>>
>> Instead:
>>
>>        return self.__class__(x, y)  # Better.
> 
> This would work if you were dealing with the intersection of two points,
> but how do you use that sort of trick for different classes?

There's nothing in the above that assumes that other has the same type as 
self. It's just that the type of other is ignored, and the type of self 
always wins. I find that a nice, clear rule: x.intersection(y) always 
returns a point with the same type as x.

If you want a more complicated rule, you have to code it yourself:


def intersection(self, other):
    if issubclass(type(other), type(self)):
        kind = type(other)
    elif issubclass(type(self), type(other)):
        kind = AbstractPoint
    elif other.__class__ is UserPoint:
        kind = UserPoint
    elif today is Tuesday:
        kind = BelgiumPoint
    else:
        kind = self.__class__
    return kind(x, y)


-- 
Steven



More information about the Python-list mailing list