Python引用计数

Python里object都会有一个属性:被引用次数,垃圾回收的时候会用到,最简单的情形是引用计数=0,直接回收掉即可。其他复杂些的情形,如循环引用,则需要通过标记-清除和分代回收机制来进行。
sys.getrefcount(obj)可以查看一个object被引用的次数。有趣的是它给出的结果总是比实际数目多1,原因是调用函数时也增加了一次引用。
其文档https://docs.python.org/3.7/library/sys.html#sys.getrefcount是如此描述的:

sys.getrefcount(object)
Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

“generally one higher”,是说一般情况下会多一,但特殊情况不会多?否则直接减一然后返回实际值就行了?
值得研究一下。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注