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

(original) (raw)

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@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
� � 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