Overloading operators

Aaron "Castironpi" Brady castironpi at gmail.com
Wed Oct 15 12:30:05 EDT 2008


On Oct 15, 7:34 am, 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?

Multimethods do the thing you're looking for.  Google: 'python
multimethods' gives:

http://www.artima.com/weblogs/viewpost.jsp?thread=101605

by van Rossum.  Some examples:

from mm import multimethod

@multimethod(int, int)
def foo(a, b):
    ...code for two ints...

@multimethod(float, float):
def foo(a, b):
    ...code for two floats..

It is especially good if you're using inheritance.  You could also
collect the names of the types, and call a function by name:

(untested)
fname= a.__class__.__name__+ '_'+ b.__class__.__name__
or
fname= re.sub( '[^a-Za-z0-9]+', '', str( type( a ) ) ) + same
type( b )
ffunc= getattr( namespace, fname )

or build a dictionary.

(untested)
f= {}
f[ int, int ]= compA
f[ int, str ]= compB
...
ffunc= f[ type( a ), type( b ) ]

What's your favorite?



More information about the Python-list mailing list