py: Implement getattr() builtin.

This commit is contained in:
Paul Sokolovsky 2014-03-26 23:35:13 +02:00
parent 9b196cddab
commit e9137b94f2
5 changed files with 25 additions and 0 deletions

View File

@ -381,3 +381,10 @@ STATIC mp_obj_t mp_builtin_id(mp_obj_t o_in) {
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_id_obj, mp_builtin_id);
STATIC mp_obj_t mp_builtin_getattr(mp_obj_t o_in, mp_obj_t attr) {
assert(MP_OBJ_IS_QSTR(attr));
return rt_load_attr(o_in, MP_OBJ_QSTR_VALUE(attr));
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_getattr_obj, mp_builtin_getattr);

View File

@ -12,6 +12,7 @@ MP_DECLARE_CONST_FUN_OBJ(mp_builtin_dir_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_divmod_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_eval_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_exec_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_getattr_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_hash_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_id_obj);
MP_DECLARE_CONST_FUN_OBJ(mp_builtin_isinstance_obj);

View File

@ -60,6 +60,7 @@ STATIC const mp_builtin_elem_t builtin_object_table[] = {
{ MP_QSTR_divmod, (mp_obj_t)&mp_builtin_divmod_obj },
{ MP_QSTR_eval, (mp_obj_t)&mp_builtin_eval_obj },
{ MP_QSTR_exec, (mp_obj_t)&mp_builtin_exec_obj },
{ MP_QSTR_getattr, (mp_obj_t)&mp_builtin_getattr_obj },
{ MP_QSTR_hash, (mp_obj_t)&mp_builtin_hash_obj },
{ MP_QSTR_id, (mp_obj_t)&mp_builtin_id_obj },
{ MP_QSTR_isinstance, (mp_obj_t)&mp_builtin_isinstance_obj },

View File

@ -92,6 +92,7 @@ Q(eval)
Q(exec)
Q(filter)
Q(float)
Q(getattr)
Q(hash)
Q(id)
Q(int)

15
tests/basics/getattr1.py Normal file
View File

@ -0,0 +1,15 @@
class A:
var = 132
def __init__(self):
self.var2 = 34
def meth(self, i):
return 42 + i
a = A()
print(getattr(a, "var"))
print(getattr(a, "var2"))
print(getattr(a, "meth")(5))