Question about overloading of binary operators

gigs gigs at hi.t-com.hr
Mon Mar 31 18:03:54 EDT 2008


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



More information about the Python-list mailing list