弱引用对象¶
Python 支持 “弱引用” 作为一类对象。具体来说,有两种直接实现弱引用的对象。第一种就是简单的引用对象,第二种尽可能地作用为一个原对象的代理。
-
PyObject *PyWeakref_NewRef(PyObject *ob, PyObject *callback)¶
- 返回值:新的引用。 属于 稳定 ABI.
Return a weak reference object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing reference object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
None
orNULL
. If ob is not a weakly referenceable object, or if callback is not callable,None
, orNULL
, this will returnNULL
and raiseTypeError
.
-
PyObject *PyWeakref_NewProxy(PyObject *ob, PyObject *callback)¶
- 返回值:新的引用。 属于 稳定 ABI.
Return a weak reference proxy object for the object ob. This will always return a new reference, but is not guaranteed to create a new object; an existing proxy object may be returned. The second parameter, callback, can be a callable object that receives notification when ob is garbage collected; it should accept a single parameter, which will be the weak reference object itself. callback may also be
None
orNULL
. If ob is not a weakly referenceable object, or if callback is not callable,None
, orNULL
, this will returnNULL
and raiseTypeError
.
-
PyObject *PyWeakref_GetObject(PyObject *ref)¶
- 返回值:借入的引用。 属于 稳定 ABI.
返回弱引用 ref 的被引用对象。 如果被引用对象不再存在,则返回
Py_None
。备注
该函数返回被引用对象的一个 borrowed reference。 这意味着应该总是在该对象上调用
Py_INCREF()
,除非是当它在借入引用的最后一次被使用之前无法被销毁的时候。
-
PyObject *PyWeakref_GET_OBJECT(PyObject *ref)¶
- 返回值:借入的引用。
类似于
PyWeakref_GetObject()
,但是不带错误检测。
-
void PyObject_ClearWeakRefs(PyObject *object)¶
- 属于 稳定 ABI.
此函数将被
tp_dealloc
处理器调用以清空弱引用。此函数将迭代 object 的弱引用并调用这些引用中可能存在的回调。 它将在尝试了所有回调之后返回。