CPython 2.7中PyObject.ob_type的初始化与设置机制问询
ob_type Field for Objects Great question—let’s dig into how CPython sets up the ob_type field that makes your isinstance check work as expected.
First, let’s recap your example to ground this:
- You have
lib2.X, a new-style class inheriting fromobject - When you create
ob = lib2.X(),isinstance(ob, lib2.X)returnsTrue, which lines up with the CPython source check you found:if (Py_TYPE(inst) == (PyTypeObject *)cls) return 1;
Here’s how ob_type gets initialized at startup and during object creation:
1. Class Objects Get Their ob_type Set First
When you define class X(object) in lib2.py, CPython executes this class definition using the metatype type (represented in C as PyType_Type). The metatype’s __new__ method creates a PyTypeObject instance (this is your X class itself). During this process:
- The
ob_typefield of theXclass object is set to point toPyType_Type(since all classes are instances oftype). - All the class’s metadata (like attributes, base classes, etc.) is initialized here too.
2. Instance Objects Have ob_type Set on Creation
When you call lib2.X() to create an instance:
- CPython calls the class’s
__new__method (by default,object.__new__for new-style classes) to allocate memory for the new object. - Immediately after memory is allocated, the underlying C code sets the instance’s
ob_typefield directly to thePyTypeObjectof the class that created it—in this case,lib2.X. This happens in low-level functions likePyObject_NeworPyObject_Init, where the class is passed as an argument and assigned to the instance’sob_type.
That’s why your check works: the instance ob has ob_type pointing exactly to lib2.X, so the equality check in the C source returns 1, making isinstance return True.
For new-style classes (like your X), this direct ob_type assignment is straightforward. Old-style classes in Python 2 have a slightly more complex lookup chain, but since you’re using a new-style class, this direct match is all that’s needed.
内容的提问来源于stack exchange,提问作者JoJo

