V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
tttty
V2EX  ›  Python

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

  •  
  •   tttty · 2017-04-19 19:40:02 +08:00 · 2765 次点击
    这是一个创建于 2569 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    7 条回复    2017-04-20 14:07:18 +08:00
    tttty
        1
    tttty  
    OP
       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
        2
    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 机制保存了之前的常量?你可以试着关闭解释器,重新启动再查看下。
    tttty
        4
    tttty  
    OP
       2017-04-19 23:52:39 +08:00
    @Daetalus 这个我有试过,还是奇怪的数字,本来应该是 2..
    binux
        5
    binux  
       2017-04-20 05:12:09 +08:00
    ipython 对于最近输入输出有缓存的,你输入 locals() 就知道了
    XYxe
        6
    XYxe  
       2017-04-20 09:58:17 +08:00
    这是 ipython 的问题,直接用 python 是不会有这种情况的.
    和 intern 机制也没关系,intern 默认只会对长度为 0 和 1 以及调用 PyString_InternFromString 创建的字符串进行 intern 处理.
    tttty
        7
    tttty  
    OP
       2017-04-20 14:07:18 +08:00
    @binux
    @XYxe 谢谢,已解决。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2408 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:14 · PVG 23:14 · LAX 08:14 · JFK 11:14
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.