[Python-Dev] summing integer and class

Xavier Morel python-dev at masklinn.net
Thu Oct 3 17:54:48 CEST 2013


On 2013-10-03, at 15:45 , Igor Vasilyev 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:
> 

python-dev is about developing Python itself, not about developing in
Python, so that's the wrong mailing list for these kinds of question.

But FWIW the answer is that Python first tries 1.__add__(a), when that
fails (with NotImplemented) it uses the reflected method[0] which is
a.__radd__(1). Since that does not exist, the operation is invalid.

[0] http://docs.python.org/2/reference/datamodel.html#object.__radd__


More information about the Python-Dev mailing list