Designing superclasses so inherited methods return objects with same type as the instance.

Felix T. Fjt72701 at yahoo.com
Wed Nov 19 16:51:45 EST 2008


I have a class called Interval(type.ObjectType) that is supposed to
mimic closed mathematical intervals. Right now, it has a lot of
methods like this:

    def __add__(self,other):
        if type(other) in Numerical:
            return Interval(self.lower_bound+other, self.upper_bound
+other)
        else:
            return Interval(self.lower_bound+other.lower_bound,
                            self.upper_bound+other.upper_bound)

that return new objects of the same type.

The problem is that if this method is called by a subclass like

class HalfOpen(Interval):
      #new comparison methods
      ...
it returns an object with Interval (not HalfOpen) type.


I either have to redefine methods like __add__ so that they return
objects of the right type (even though the logic is the same) or find
some way to redefine Interval's methods so they are more flexible.
Right now, I am looking at:

    def __add__(self,other):
        if type(other) in Numerical:
            return self.__class__(self.lower_bound+other,
self.upper_bound+other)
        else:
            return self.__class__(self.lower_bound+other.lower_bound,
                            self.upper_bound+other.upper_bound)

Is there a standard way to do this, or a better one?

Thanks in advance,
Felix



More information about the Python-list mailing list