From e9137b94f27594ea1bdeb5fa4eaddffcbb7b9e9a Mon Sep 17 00:00:00 2001 From: Paul Sokolovsky Date: Wed, 26 Mar 2014 23:35:13 +0200 Subject: [PATCH] py: Implement getattr() builtin. --- py/builtin.c | 7 +++++++ py/builtin.h | 1 + py/builtintables.c | 1 + py/qstrdefs.h | 1 + tests/basics/getattr1.py | 15 +++++++++++++++ 5 files changed, 25 insertions(+) create mode 100644 tests/basics/getattr1.py diff --git a/py/builtin.c b/py/builtin.c index fe9757fdf3..f9775a55a7 100644 --- a/py/builtin.c +++ b/py/builtin.c @@ -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); diff --git a/py/builtin.h b/py/builtin.h index 45da172d10..50269dfe1f 100644 --- a/py/builtin.h +++ b/py/builtin.h @@ -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); diff --git a/py/builtintables.c b/py/builtintables.c index 0aa0b66a72..fd94f76783 100644 --- a/py/builtintables.c +++ b/py/builtintables.c @@ -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 }, diff --git a/py/qstrdefs.h b/py/qstrdefs.h index a2cdf84251..3be6295067 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -92,6 +92,7 @@ Q(eval) Q(exec) Q(filter) Q(float) +Q(getattr) Q(hash) Q(id) Q(int) diff --git a/tests/basics/getattr1.py b/tests/basics/getattr1.py new file mode 100644 index 0000000000..7b7e073922 --- /dev/null +++ b/tests/basics/getattr1.py @@ -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))