Overloading operators

Aaron "Castironpi" Brady castironpi at gmail.com
Wed Oct 15 19:12:47 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?

Off topic.
For the record, the solution in C is pretty bad without using true
overloading.  There's no literal hash, and you have to carry your
types with your variables, possibly using a union.  But if so, you can
use an enum and an array.  This owes to the uniformity of function
signatures of the comparitors you're using.

(uncompiled)

typedef ( int comparitor_t* )( void* ob1, void* ob2 );
comparitor_t comparitors[]= { compare_ints, compare_strs /*,
others*/ };
enum comparison_types {
  ints= 0,
  strs= 1
};
struct variant {
  comparison_types type;
  union {
    int i;
    str s;
  };
};

int compare( variant& a, variant& b ) {
  assert( a.type== b.type );
  return comparitors[ a.type ]( a, b );
}

'compare' knows how to retrieve its members from the union.  The 'int'
comparitor accesses the 'i' field, &c.  Your compiler needs to know
that enums are ints or that they can be indices into an array.

For BASIC and even VisualBasic up to version 6, you have no choice but
use a switch statement.  The addressof operator won't help since
you're not calling DLL entry points.  VisualBasic.NET claims to
overload functions.  But C++ and VB can both employ the Visitor
pattern "double-dispatch".  It would be good practice to use Visitor
to keep your options open across more languages, except that it's kind
of trivial in Python, oddly enough.  Good middle ground, I guess.



More information about the Python-list mailing list