Overloading operators

Kay Schluehr kay.schluehr at gmx.net
Thu Oct 16 00:22:55 EDT 2008


On 15 Okt., 14:34, Mr.SpOOn <mr.spoo... at gmail.com> wrote:
> Hi,
> in a project I'm overloading a lot of comparison and arithmetic
> operators to make them working with more complex classes that I
> defined.
>
> Sometimes I need a different behavior of the operator depending on the
> argument. For example, if I compare a object with an int, I get a
> result, but if I compare the same object with a string, or another
> object, I get another result.
>
> What is the best way to do this? Shall I use a lot of "if...elif"
> statements inside the overloaded operator? Or is there a more pythonic
> and dynamic way?

I can't see anything wrong about it. Sometimes I try to avoid
isinstance() though because it is a rather slow operation. If the
majority of operations is single-typed one can also use a try-stmt:

    def __add__(self, other):
        try:
            return self._val + other
        except TypeError:
            return self.__add__(SomeWrapper(other))

and compare performance using a profiler. Notice that also

    if type(obj) == T:
        BLOCK

is much faster than isinstance() but it's not OO-ish and very rigid.



More information about the Python-list mailing list