Question about overloading of binary operators

Dan Bishop danb_83 at yahoo.com
Tue Apr 1 03:56:07 CEST 2008


On Mar 31, 5:03 pm, gigs <g... at hi.t-com.hr> wrote:
> Raj Bandyopadhyay wrote:
> > Hi
>
> > Here's a simple class example I've defined
>
> > #############################
> > class myInt(int):
> >    def __add__(self,other):
> >       return 0
>
> > print 5 + myInt(4)   #prints 9
> > print myInt(4) + 5   #prints 0
> > #############################
>
> > The Python binary operation function (binary_op1() in
> > Objects/abstract.c) states
> > the rules for binary operations as follows:
>
> > v w   Action
> >  -------------------------------------------------------------------
> >  new   new w.op(v,w)[*], v.op(v,w), w.op(v,w)
> >  new   old v.op(v,w), coerce(v,w), v.op(v,w)
> >  old   new w.op(v,w), coerce(v,w), v.op(v,w)
> >  old   old coerce(v,w), v.op(v,w)
>
> >  [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
> >      v->ob_type
>
> > It seems that my example should fall in case 1, and in both cases, the
> > __add__ function of the subclass should be used, returning 0, regardless
> > of operand order. However, in one case the subclass's function is used
> > and not in the other case. What am I missing here?
>
> > Thanks
> > Raj
>
> i think that you need to use __radd__ for addition with custom object on right

Right.  Python doesn't make any assumptions that addition is
commutative.

But if it is for your class, you can just write

    __radd__ = __add__



More information about the Python-list mailing list