registering python special methods in C class
Posted: Wed Jun 26, 2019 6:38 pm
Hi all,
I am trying to implement a class in C, and would like to implement the special method __add__(). I was hoping that
would be evaluated, if
However, I get the following traceback:
Curiously,
does work as expected. Here is my implementation of __add__():
and then the function is added to the local dictionary as
What I don't quite understand is why the expression
doesn't even call the method .__add__(). If it did, then I should see the four printouts, which is not the case.
The class structure is defined as
On the other hand, if I define the class in python as
then
returns 2, as expected. What the heck is going on here? Have I got to register test_add/test_add_obj in a different way?
I have also looked at the micropython code, but it seems to me that the only place, where __add__ appears is objtype.c, and I am not any wiser by reading the code there.
Well, if anyone could shed some light on this problem, I would appreciate it. I would even go as far as offering a free beer, if we bump into each other somewhere
Thanks,
Zoltán
I am trying to implement a class in C, and would like to implement the special method __add__(). I was hoping that
Code: Select all
a+b
Code: Select all
a = testObj()
b = testObj()
Code: Select all
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported types for __add__: 'testObj', 'testObj'
Code: Select all
a.__add__(b)
Code: Select all
STATIC mp_obj_t test_add(mp_obj_t self_in, mp_obj_t other_in) {
test_obj_t *self = MP_OBJ_TO_PTR(self_in);
printf("here 1\n");
test_obj_t *other = MP_OBJ_TO_PTR(other_in);
printf("here 2\n");
self->n += 1;
printf("here 3\n");
other->n += 1;
printf("here 4\n");
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(test_add_obj, test_add);
Code: Select all
{ MP_ROM_QSTR(MP_QSTR___add__), MP_ROM_PTR(&test_add_obj) },
Code: Select all
a+b
The class structure is defined as
Code: Select all
typedef struct _test_obj_t {
mp_obj_base_t base;
uint8_t n;
} test_obj_t;
Code: Select all
class T:
def __init__(self):
self.n = 1
def __add__(self, other):
return self.n + other.n
Code: Select all
a, b = T(), T()
a+b
I have also looked at the micropython code, but it seems to me that the only place, where __add__ appears is objtype.c, and I am not any wiser by reading the code there.
Well, if anyone could shed some light on this problem, I would appreciate it. I would even go as far as offering a free beer, if we bump into each other somewhere
Thanks,
Zoltán