參照計數¶
The macros in this section are used for managing reference counts of Python objects.
-
void
Py_INCREF
(PyObject *o)¶ 增加对象 o 的引用计数。 对象必须不为
NULL
;如果你不确定它不为NULL
,可使用Py_XINCREF()
。
-
void
Py_DECREF
(PyObject *o)¶ 减少对象 o 的引用计数。 对象必须不为
NULL
;如果你不确定它不为NULL
,可使用Py_XDECREF()
。 如果引用计数降为零,将发起调用对象所属类型的释放函数 (它必须不为NULL
)。警告
The deallocation function can cause arbitrary Python code to be invoked (e.g. when a class instance with a
__del__()
method is deallocated). While exceptions in such code are not propagated, the executed code has free access to all Python global variables. This means that any object that is reachable from a global variable should be in a consistent state beforePy_DECREF()
is invoked. For example, code to delete an object from a list should copy a reference to the deleted object in a temporary variable, update the list data structure, and then callPy_DECREF()
for the temporary variable.
-
void
Py_XDECREF
(PyObject *o)¶ 减少对象 o 的引用计数。 对象可以为
NULL
,在此情况下该宏不产生任何效果;在其他情况下其效果与Py_DECREF()
相同,并会应用同样的警告。
-
void
Py_CLEAR
(PyObject *o)¶ 减少对象 o 的引用计数。 对象可以为
NULL
,在此情况下该宏不产生任何效果;在其他情况下其效果与Py_DECREF()
相同,区别在于其参数也会被设为NULL
。 针对Py_DECREF()
的警告不适用于所传递的对象,因为该宏会细心地使用一个临时变量并在减少其引用计数之前将参数设为NULL
。每当要减少在垃圾回收期间可能会被遍历的对象的引用计数时,使用该宏是一个好主意。
The following functions are for runtime dynamic embedding of Python:
Py_IncRef(PyObject *o)
, Py_DecRef(PyObject *o)
. They are
simply exported function versions of Py_XINCREF()
and
Py_XDECREF()
, respectively.
The following functions or macros are only for use within the interpreter core:
_Py_Dealloc()
, _Py_ForgetReference()
, _Py_NewReference()
,
as well as the global variable _Py_RefTotal
.