confusion with __add__ and __radd__

Walter Moreira walterm at parque.homelinux.net
Tue Dec 3 15:43:18 EST 2002


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?

Thanks in advance.
Walter




More information about the Python-list mailing list