[Python-Dev] summing integer and class (original) (raw)
Chris Kaynor ckaynor at zindagigames.com
Thu Oct 3 17:58:44 CEST 2013
- Previous message: [Python-Dev] summing integer and class
- Next message: [Python-Dev] summing integer and class
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 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-dev/attachments/20131003/7fff1e0f/attachment.html>
- Previous message: [Python-Dev] summing integer and class
- Next message: [Python-Dev] summing integer and class
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]