Overloading operators

Robert Lehmann stargaming at gmail.com
Wed Oct 15 18:35:43 CEST 2008


On Wed, 15 Oct 2008 14:34:14 +0200, Mr.SpOOn 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?

If all your comparison methods do more or less the same (even if not but 
then it will be kinda less useful for complex operations) you could use 
dictionary-based dispatching. You would basically construct a dictionary 
of type->comparator mappings, like this::

    dispatch = {
        int: int_compare_function,
        str: str_compare_function,
    }

And dispatch according to the other object's type::

    def __cmp__(self, other):
        return dispatch[type(other)]()

(Assuming good faith and just throwing a `KeyError` for unimplemented 
types.)

If you just needed to dispatch on a special attribute depending on the 
other object's type, you could redesign the dispatch dictionary to be a 
type->attribute mapping and go somewhere along this way::

    dispatch = {
        int: 'value',
        str: 'name',
    }
    def __cmp__(self, other):
        return cmp(getattr(self, dispatch[type(other)]), other)

HTH,

-- 
Robert "Stargaming" Lehmann



More information about the Python-list mailing list