Skip to content

Commit d47f9d5

Browse files
committed
py: add call to __init__ when instantiating class object.
1 parent c1075dd commit d47f9d5

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

py/runtime.c

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1757,15 +1757,41 @@ py_obj_t rt_call_function_n(py_obj_t fun, int n_args, const py_obj_t *args) {
17571757

17581758
} else if (IS_O(fun, O_CLASS)) {
17591759
// instantiate an instance of a class
1760-
if (n_args != 0) {
1761-
n_args_fun = 0;
1762-
goto bad_n_args;
1763-
}
1764-
DEBUG_OP_printf("instantiate object of class %p with no args\n", fun);
1760+
1761+
DEBUG_OP_printf("instantiate object of class %p with %d args\n", fun, n_args);
17651762
py_obj_base_t *o = m_new(py_obj_base_t, 1);
17661763
o->kind = O_OBJ;
17671764
o->u_obj.class = fun;
17681765
o->u_obj.members = py_map_new(MAP_QSTR, 0);
1766+
1767+
// look for __init__ function
1768+
py_obj_base_t *o_class = fun;
1769+
py_map_elem_t *init_fn = py_qstr_map_lookup(o_class->u_class.locals, qstr_from_str_static("__init__"), false);
1770+
1771+
if (init_fn != NULL) {
1772+
// call __init__ function
1773+
py_obj_t init_ret;
1774+
if (n_args == 0) {
1775+
init_ret = rt_call_function_n(init_fn->value, 1, (py_obj_t*)&o);
1776+
} else {
1777+
py_obj_t *args2 = m_new(py_obj_t, n_args + 1);
1778+
memcpy(args2, args, n_args * sizeof(py_obj_t));
1779+
args2[n_args] = o;
1780+
init_ret = rt_call_function_n(init_fn->value, n_args + 1, args2);
1781+
m_free(args2);
1782+
}
1783+
if (init_ret != py_const_none) {
1784+
nlr_jump(py_obj_new_exception_2(q_TypeError, "__init__() should return None, not '%s'", py_obj_get_type_str(init_ret), NULL));
1785+
}
1786+
1787+
} else {
1788+
// TODO
1789+
if (n_args != 0) {
1790+
n_args_fun = 0;
1791+
goto bad_n_args;
1792+
}
1793+
}
1794+
17691795
return o;
17701796

17711797
} else {

0 commit comments

Comments
 (0)