[Python-Dev] summing integer and class (original) (raw)
Игорь Васильев vasilyev_igor at inbox.ru
Thu Oct 3 15:09:31 CEST 2013
- Previous message: [Python-Dev] project culture: take responsibility for your commits
- Next message: [Python-Dev] summing integer and class
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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:
static PyObject * binary_op1(PyObject *v, PyObject *w, const int op_slot) { PyObject *x; binaryfunc slotv = NULL; binaryfunc slotw = NULL;
if (v->ob_type->tp_as_number != NULL) slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot); if (w->ob_type != v->ob_type && w->ob_type->tp_as_number != NULL) { slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot); if (slotw == slotv) slotw = NULL; } if (slotv) { if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); /* can't do it / slotw = NULL; } x = slotv(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); / can't do it / } if (slotw) { x = slotw(v, w); if (x != Py_NotImplemented) return x; Py_DECREF(x); / can't do it */ } Py_RETURN_NOTIMPLEMENTED; }
When we adding class to integer we have both slotv and slotw. x = slotv(v, w); -> returns Py_NotImplemented. But in this case we should execute x = slotw(v, w); and function should be completed in the same way as when we adding integer to class.
Can someone advise please where I mistake.
-- thanks, Igor Vasilyev -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20131003/e193b04f/attachment.html>
- Previous message: [Python-Dev] project culture: take responsibility for your commits
- Next message: [Python-Dev] summing integer and class
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]