Access 'class' data from instance or class methods

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
Posts: 54
Joined: Wed Jan 31, 2018 3:10 pm

Access 'class' data from instance or class methods

Post by BramPeeters » Wed Sep 12, 2018 12:37 pm


Class methods (cfr MP_DEFINE_CONST_CLASSMETHOD_OBJ) have a first argument 'class' when being called.

In none of the code where MP_DEFINE_CONST_CLASSMETHOD_OBJ is used in the micropython codebase, something seems to be done with this first argument (which means that all these could be replaced by static methods I think).

Anyway, since the difference between class and static methods is that one is suppose to be able to access 'class' data, i was wondering how to do that. How do i use this first 'cls' argument to access class level data?

STATIC mp_obj_t my_class_method( mp_obj_t cls , mp_obj_t arg1, mp_obj_t arg2)
// store arg1 and arg2 in the class data
... ??
STATIC MP_DEFINE_CONST_FUN_OBJ_3(mp_obj_t my_class_method_fun_obj, mp_obj_t my_class_method);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(mp_obj_t my_class_method_obj, (const mp_obj_t)&mp_obj_t my_class_method_fun_obj);

As far as i understand (?) cls if of the type
typedef struct _mp_obj_static_class_method_t {
mp_obj_base_t base;
mp_obj_t fun;
} mp_obj_static_class_method_t;
But i do not immediately see a way to some class level dictionary or something like i was expecting ?

Similarly it should be possible to access the class data from within an instance method. How do i do that ?
STATIC my_instance_method( mp_obj_t self , mp_obj_t arg1, mp_obj_t arg2)
// store arg1 and arg2 in the class data of the class corresponding the the 'self' instance
... ??
STATIC MP_DEFINE_CONST_FUN_OBJ_3(my_instance_method_obj, my_instance_method);

Post Reply