py/objtype: Support full object model for get/set/delitem special meths.

This makes these special methods have the same calling behaviour as other
methods in a class instance (mp_convert_member_lookup() is already called
by mp_obj_class_lookup()).
This commit is contained in:
Damien George 2018-09-28 23:16:56 +10:00
parent 2eb0170157
commit dd288904db
2 changed files with 19 additions and 11 deletions

View File

@ -797,36 +797,29 @@ STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t member[2] = {MP_OBJ_NULL};
mp_obj_t member[4] = {MP_OBJ_NULL, MP_OBJ_NULL, index, value};
struct class_lookup_data lookup = {
.obj = self,
.meth_offset = offsetof(mp_obj_type_t, subscr),
.dest = member,
.is_type = false,
};
size_t meth_args;
if (value == MP_OBJ_NULL) {
// delete item
lookup.attr = MP_QSTR___delitem__;
mp_obj_class_lookup(&lookup, self->base.type);
meth_args = 2;
} else if (value == MP_OBJ_SENTINEL) {
// load item
lookup.attr = MP_QSTR___getitem__;
mp_obj_class_lookup(&lookup, self->base.type);
meth_args = 2;
} else {
// store item
lookup.attr = MP_QSTR___setitem__;
mp_obj_class_lookup(&lookup, self->base.type);
meth_args = 3;
}
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_SENTINEL) {
return mp_obj_subscr(self->subobj[0], index, value);
} else if (member[0] != MP_OBJ_NULL) {
mp_obj_t args[3] = {self_in, index, value};
// TODO probably need to call mp_convert_member_lookup, and use mp_call_method_n_kw
mp_obj_t ret = mp_call_function_n_kw(member[0], meth_args, 0, args);
size_t n_args = value == MP_OBJ_NULL || value == MP_OBJ_SENTINEL ? 1 : 2;
mp_obj_t ret = mp_call_method_n_kw(n_args, 0, member);
if (value == MP_OBJ_SENTINEL) {
return ret;
} else {

View File

@ -17,9 +17,24 @@ class C:
def __add__(self, rhs):
print('add', rhs)
# subscript special methods wrapped in staticmethod
@staticmethod
def __getitem__(item):
print('static get', item)
return 'item'
@staticmethod
def __setitem__(item, value):
print('static set', item, value)
@staticmethod
def __delitem__(item):
print('static del', item)
c = C()
c.f(0)
c.g(0)
c - 1
c + 2
print(c[1])
c[1] = 2
del c[3]