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

2017-04-19 19:40:02 +08:00
 tttty

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 而且两者还不一样。谢谢各位前辈们。

2782 次点击
所在节点    Python
7 条回复
tttty
2017-04-19 20:17:11 +08:00
In [1]: import sys

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

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

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

我觉得有毒
Daetalus
2017-04-19 20:29:43 +08:00
@tttty
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 机制保存了之前的常量?你可以试着关闭解释器,重新启动再查看下。
Mistwave
2017-04-19 20:31:50 +08:00
tttty
2017-04-19 23:52:39 +08:00
@Daetalus 这个我有试过,还是奇怪的数字,本来应该是 2..
binux
2017-04-20 05:12:09 +08:00
ipython 对于最近输入输出有缓存的,你输入 locals() 就知道了
XYxe
2017-04-20 09:58:17 +08:00
这是 ipython 的问题,直接用 python 是不会有这种情况的.
和 intern 机制也没关系,intern 默认只会对长度为 0 和 1 以及调用 PyString_InternFromString 创建的字符串进行 intern 处理.
tttty
2017-04-20 14:07:18 +08:00
@binux
@XYxe 谢谢,已解决。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/355988

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX