Code: Select all
>>>class test:
>>> testint = 10;
I want to call it in python with
Code: Select all
>>>testvar = test()
>>>testvar.testint
10
Could somebody help me?
Thanks Scalli
Code: Select all
>>>class test:
>>> testint = 10;
Code: Select all
>>>testvar = test()
>>>testvar.testint
10
Your example is slightly ambiguous: are you interested in class variables or instance variables?Scalli wrote: ↑Thu Aug 02, 2018 12:49 pmHi I try to implement a Micropython C Class and I wonder if there is a posibillity, to generate a class like this:In C code.Code: Select all
>>>class test: >>> testint = 10;
I want to call it in python withI know the implementation of a class but not how to make a Variable callable like this.Code: Select all
>>>testvar = test() >>>testvar.testint 10
Could somebody help me?
Thanks Scalli
Code: Select all
const mp_obj_type_t mp_type_module = {
{ &mp_type_type },
.name = MP_QSTR_module,
.print = module_print,
.attr = module_attr,
};
Code: Select all
typedef struct _mp_obj_module_t {
mp_obj_base_t base;
mp_obj_dict_t *globals;
} mp_obj_module_t;
Code: Select all
const mp_obj_type_t mp_type_test = {
{ &mp_type_type },
.name = MP_QSTR_test,
.print = test_print,
.attr = test_attr,
.make_new = test_make_new // THIS IS DIFFERENT FROM ABOVE
};
Code: Select all
typedef struct _mp_obj_test_t {
mp_obj_base_t base;
mp_obj_dict_t *globals;
} mp_obj_test_t;
Code: Select all
STATIC mp_obj_t test_make_new (const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
(void)type_in;
mp_arg_check_num(n_args, n_kw, 0, 0, false);
// Create the C-obj
mp_obj_test_t * test = m_new_obj(mp_obj_test_t);
// Set the base
test->base.type = &mp_type_test;
// Create the dictionary to hold instance variables
test->globals = MP_OBJ_TO_PTR(mp_obj_new_dict(0));
// Now add the members one by one
mp_obj_dict_store(MP_OBJ_FROM_PTR(test ->globals), MP_OBJ_NEW_QSTR(MP_QSTR_testint), MP_OBJ_NEW_SMALL_INT(0));
return MP_OBJ_FROM_PTR(test);
}
Code: Select all
class test:
testint = 1
print(test.testint)
Yes but if you define .attr you still have to add code in .attr to read from locals_dictstijn wrote:If you want a static class variable on the other hand, i.e. the equivalent of
you just have to add it to the type's locals_dictCode: Select all
class test: testint = 1 print(test.testint)
Hmm, in what circumstances would .attr be called when there isn't an instance of the class yet?
It wouldn't. Didn't mean to imply that.
Yes I agree.
For an mp_type_type, dir() only needs to look at .locals_dict but for an instance it's not enough.
Code: Select all
class test:
testint = 1
def __init__(self, unique_int):
self.unique = unique_int