问题
I understand that everything in python is an Object and that the 'type' (or class) of these object is 'type'. Plus the type of type is also type itself. (as explained nicely here)
What I do not understand is how is this circular reference implemented? So i looked here. To quote the portion which might explain what I am looking for:
PyTypeObject* PyObject.ob_type
This is the type’s type, in other words its metatype. It is initialized by the argument to the PyObject_HEAD_INIT macro, and its value should normally be &PyType_Type. However, for dynamically loadable extension modules that must be usable on Windows (at least), the compiler complains that this is not a valid initializer. Therefore, the convention is to pass NULL to the PyObject_HEAD_INIT macro and to initialize this field explicitly at the start of the module’s initialization function, before doing anything else. This is typically done like this:
Foo_Type.ob_type = &PyType_Type;
Since C is not OOP based, I understand that when one creates a class, it can have an attribute to point to the object itself as its own class. I am sure that my lack of understanding here has led me in a state of confusion, can anyone point out if this is a usual practice in design of other scripting languages or some kind of a pattern, if anyone can throw some light on this, I will be grateful for it.
EDIT : I found out here that:
PyObject* PyType_Type
This is the type object for type objects; it is the same object as type and types.TypeType in the Python layer.
How is that?
回答1:
The code that defines PyType_Type.ob_type = &PyType_Type involves a couple of indirections. It all starts in the function _Py_ReadyTypes()
when it calls PyType_Ready(&PyType_Type)
. Before the function is called, the members tp_base
and ob_type
are both NULL
. The function first sets type->tp_base
to &PyBaseObject_Type
(which is object
in Python space) and then sets type->ob_type = PyBaseObject_Type.ob_type
. The code uses Py_TYPE()
which is just a macro for ob->ob_type
. Since the type of object is type the code sets the type of type to type.
Now you have:
>>> type.__bases__
(<class 'object'>,)
>>> type(object)
<class 'type'>
>>> type(type(object))
<class 'type'>
The definition makes type an instance of object plus itself and object an instance of type.
>>> isinstance(type, object)
True
>>> isinstance(object, type)
True
>>> isinstance(type, type)
True
The type initialization code is much easier to understand in Python pseudo-code:
# object's class is type
object.__class__ = type
# PyType_Ready(type) sets:
type.__bases__ = (object,)
type.__class__ = type(object)
来源:https://stackoverflow.com/questions/18692033/how-does-cpython-implement-its-type-objects-i-e-types-type-is-always-type