confusion with __add__ and __radd__ [SOLVED]
Walter Moreira
walterm at parque.homelinux.net
Sat Dec 7 12:05:23 EST 2002
On Tue, Dec 03, 2002 at 05:43:18PM -0300, Walter Moreira wrote:
> Hello. I'm confused about the behavior of the 'reverse' methods
> __radd__, __rmul__, etc, and Google didn't help me.
>
>
> Python 2.2.2 (#1, Nov 21 2002, 08:18:14)
> [GCC 2.95.4 20011002 (Debian prerelease)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
> >>> class Foo(object):
> ... def __add__(self, other):
> ... print 'add'
> ... return NotImplemented
> ... def __radd__(self, other):
> ... print 'radd'
> ... return 1
> ...
> >>>
> >>>
> >>> a=Foo()
> >>> b=Foo()
> >>> a+b
> add
> add
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: unsupported operand types for +: 'Foo' and 'Foo'
> >>>
>
> Why isn't the __radd__ method called, since __add__ returns
> 'NotImplemented'? If 'Foo' is a classic class it works ok. Am I
> overlooking something obvious?
Just for the record. I read the sources and I found that when the type
of new style objects is the same, then only the slots of the left operand
are tried. I don't fully understand the reason (but that's another
question).
So, if I define a 'Bar' class in the same way as 'Foo' above, then 'a+b'
correctly calls Foo.__add__ and then Bar.__radd__.
Walter.
More information about the Python-list
mailing list