# 參照計數

本节介绍的宏被用于管理 Python 对象的引用计数。

void `Py_INCREF`( PyObject *o)

  Increment the reference count for object o. The object must not be NULL; if you aren’t sure that it isn’t NULL, use `Py_XINCREF()`.

void `Py_XINCREF`( PyObject *o)

  Increment the reference count for object o. The object may be NULL, in which case the macro has no effect.

void `Py_DECREF`( PyObject *o)

  Decrement the reference count for object o. The object must not be NULL; if you aren’t sure that it isn’t NULL, use `Py_XDECREF()`. If the reference count reaches zero, the object’s type’s deallocation function (which must not be NULL) is invoked.

  警告

  释放函数可导致任意 Python 代码被发起调用（例如当一个带有 `__del__()` 方法的类实例被释放时就是如此）。 虽然此类代码中的异常不会被传播，但被执行的代码能够自由访问所有 Python 全局变量。 这意味着任何可通过全局变量获取的对象在 `Py_DECREF()` 被发起调用之前都应当处于完好状态。 例如，从一个列表中删除对象的代码应当将被删除对象的引用拷贝到一个临时变量中，更新列表数据结构，然后再为临时变量调用 `Py_DECREF()`。

void `Py_XDECREF`( PyObject *o)

  Decrement the reference count for object o. The object may be NULL, in which case the macro has no effect; otherwise the effect is the same as for `Py_DECREF()`, and the same warning applies.

void `Py_CLEAR`( PyObject *o)

  Decrement the reference count for object o. The object may be NULL, in which case the macro has no effect; otherwise the effect is the same as for `Py_DECREF()`, except that the argument is also set to NULL. The warning for `Py_DECREF()` does not apply with respect to the object passed because the macro carefully uses a temporary variable and sets the argument to NULL before decrementing its reference count.

  当要减少在垃圾回收期间可能会被遍历的变量的值时，使用该宏是一个好主意。

以下函数适用于 Python 的运行时动态嵌入: `Py_IncRef(PyObject *o)`, `Py_DecRef(PyObject *o)`。 它们分别只是 `Py_XINCREF()` 和 `Py_XDECREF()` 的简单导出函数版本。

以下函数或宏仅可在解释器核心内部使用: `_Py_Dealloc()`, `_Py_ForgetReference()`, `_Py_NewReference()` 以及全局变量 `_Py_RefTotal`。