Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #55417

Re: [Python-Dev] summing integer and class

References <524D74EE.90308@oracle.com>
From Chris Kaynor <ckaynor@zindagigames.com>
Date 2013-10-03 08:58 -0700
Subject Re: [Python-Dev] summing integer and class
Newsgroups comp.lang.python
Message-ID <mailman.679.1380816353.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view 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 <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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: [Python-Dev] summing integer and class Chris Kaynor <ckaynor@zindagigames.com> - 2013-10-03 08:58 -0700

csiph-web