[Python-Dev] right-side binary operations
phd at phd.pp.ru
Fri Mar 19 14:07:34 CET 2010
On Fri, Mar 19, 2010 at 03:46:07PM +0300, Alex A. Naanou wrote:
> >>> class C(object):
> ... def __radd__(self, other):
> ... print 'C: adding C and %s objects.' % other.__class__.__name__
> >>> 1 + c
> C: adding C and int objects.
> My first expectation would be to get a TypeError here, as ints indeed
> have an __add__ method, and they do not know anything about C objects
> (obviously :) ). On second thought, giving client code priority to
> handle things has it's merits.
> The problem is that I found no mention of this behavior in the docs.
It's well-known and documented behavior. It's what r-methods are for.
"These methods are called to implement the binary arithmetic operations
(+, -, *, /, %, divmod(), pow(), **, <<, >>, &, ^, |) with reflected
(swapped) operands. These functions are only called if the left operand
does not support the corresponding operation and the operands are of
different types.  For instance, to evaluate the expression x - y, where
y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is
called if x.__sub__(y) returns NotImplemented."
Oleg Broytman http://phd.pp.ru/ phd at phd.pp.ru
Programmers don't die, they just GOSUB without RETURN.
More information about the Python-Dev