[Python-Dev] summing integer and class

Chris Kaynor ckaynor at zindagigames.com
Thu Oct 3 11:58:44 EDT 2013


This list is for development OF Python, not for development in python. For
that reason, I will redirect this to python-list as well. My actual answer
is below.

On Thu, Oct 3, 2013 at 6:45 AM, Igor Vasilyev <igor.vasilyev at oracle.com>
 wrote:

> Hi.
>
> Example test.py:
>
> class A():
>     def __add__(self, var):
>         print("I'm in A class")
>         return 5
> a = A()
> a+1
> 1+a


> Execution:
> python test.py
> I'm in A class
> Traceback (most recent call last):
>   File "../../test.py", line 7, in <module>
>     1+a
> TypeError: unsupported operand type(s) for +: 'int' and 'instance'
>
>
> So adding integer to class works fine, but adding class to integer fails.
> I could not understand why it happens. In objects/abstact.c we have the
> following function:
>

Based on the code you provided, you are only overloading the __add__
operator, which is only called when an "A" is added to something else, not
when something is added to an "A". You can also override the __radd__
method to perform the swapped addition. See
http://docs.python.org/2/reference/datamodel.html#object.__radd__ for the
documentation (it is just below the entry on __add__).

Note that for many simple cases, you could define just a single function,
which then is defined as both the __add__ and __radd__ operator. For
example, you could modify your "A" sample class to look like:

class A():
    def __add__(self, var):
        print("I'm in A")
        return 5
    __radd__ = __add__


Which will produce:
>>> a = A()
>>> a + 1
I'm in A
5
>>> 1 + a
I'm in A
5

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20131003/7fff1e0f/attachment.html>


More information about the Python-list mailing list