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


Groups > comp.lang.python > #55417 > unrolled thread

Re: [Python-Dev] summing integer and class

Started byChris Kaynor <ckaynor@zindagigames.com>
First post2013-10-03 08:58 -0700
Last post2013-10-03 08:58 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#55417 — Re: [Python-Dev] summing integer and class

FromChris Kaynor <ckaynor@zindagigames.com>
Date2013-10-03 08:58 -0700
SubjectRe: [Python-Dev] summing integer and class
Message-ID<mailman.679.1380816353.18130.python-list@python.org>

[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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web