In cpython souce code, I find that class is created by type_call, type_new and type_init, user defined init function actually stored in the namespace, then transfered to the type-> tp_dict, how and where __init__function is executed I can not figure out, can any one help?
I always thought __init__
was called in the metaclasses’ __call__
. For example:
class type:
def __call__(cls, *args, **kwargs):
obj = cls.__new__(*args, **kwargs)
obj.__init__(*args, **kwargs)
return obj
So perhaps check the implementation of type
Note that this code gets executed on class instantiation, not class creation. I imagine type.__init__
is called on class creation.
I was reading the cpython source code and try to analyze the byte code.
Initializing a new class in byte code is very simple, just one line call_function.
when no mata class specified, the new created class if of type PyType_Type, when you call the class, you get type_call function, which is same function when you created this class. in the type_call function I didn’t find anything related to the user defined init.
Definitily my analysis above is wrong somewhere, I just can not find it.
0 LOAD_BUILD_CLASS
2 LOAD_CONST 0 (0)
4 LOAD_CONST 1 (1)
6 MAKE_FUNCTION 0
8 LOAD_CONST 1 (1)
10 CALL_FUNCTION 2
12 STORE_NAME 0 (0)
14 LOAD_NAME 0 (0)
16 CALL_FUNCTION 0
18 STORE_NAME 1 (1)
Finally find the result, Type_new function will call PyType_Ready and fixup_slot_dispatchers, in later function if user defined slot function was found, slot function will be called to handle it.