You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CPython 2.7中PyObject.ob_type的初始化与设置机制问询

How CPython 2.7 Initializes the 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 from object
  • When you create ob = lib2.X(), isinstance(ob, lib2.X) returns True, 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_type field of the X class object is set to point to PyType_Type (since all classes are instances of type).
  • 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_type field directly to the PyTypeObject of the class that created it—in this case, lib2.X. This happens in low-level functions like PyObject_New or PyObject_Init, where the class is passed as an argument and assigned to the instance’s ob_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:13:29