关于 Python 引用计数机制的一个问题

In [1]: s = 'wangbicong'

In [2]: import sys

In [3]: sys.getrefcount(s) Out[3]: 3

In [4]: s2 = '123'

In [5]: sys.getrefcount(s2) Out[5]: 2

之前理解的引用计数机制是,一个对象被创建以后,引用计数从 0 变为 1 。这里为什么一个是 2 一个是 3 。为什么不是 1 而且两者还不一样。谢谢各位前辈们。


关于 Python 引用计数机制的一个问题

8 回复

In [1]: import sys

In [2]: s = '3131231231231231232131231231241241241241241241241241241kfsfsdfdsfsf
…: '

In [3]: s
Out[3]: '3131231231231231232131231231241241241241241241241241241kfsfsdfdsfsf’

In [4]: sys.getrefcount(s)
Out[4]: 8

我觉得有毒


我无法理解你的问题


Python 文档中,对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().

即调用getrefcount时会将引用技术临时增加 1 。对于 3 和 8 的来源,我猜测是由于 string 的 intern 机制保存了之前的常量?你可以试着关闭解释器,重新启动再查看下。

这个我有试过,还是奇怪的数字,本来应该是 2…

ipython 对于最近输入输出有缓存的,你输入 locals() 就知道了

这是 ipython 的问题,直接用 python 是不会有这种情况的.
和 intern 机制也没关系,intern 默认只会对长度为 0 和 1 以及调用 PyString_InternFromString 创建的字符串进行 intern 处理.


谢谢,已解决。

回到顶部