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
SimbaPeng
V2EX  ›  Python

谁能确切的解释一下这是为什么?

  •  
  •   SimbaPeng · 2017-06-18 11:37:53 +08:00 · 2610 次点击
    这是一个创建于 2503 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def test():
    a = []
    print(id(a))

    test() #4402322696
    test() #4402322696
    test() #4402322696

    为什么每次产生的地址值都一样?不是会创建新的地址值吗?
    4 条回复    2017-06-18 17:39:14 +08:00
    ruoyu0088
        1
    ruoyu0088  
       2017-06-18 11:46:19 +08:00
    被垃圾回收之后,还可以重复使用那个地址的。这是 Python 的优化。
    NoAnyLove
        2
    NoAnyLove  
       2017-06-18 12:16:15 +08:00
    我一定是遇到了一个假 Python ( 2.7.10 和 3.5.1 ):

    ```
    >>> def test():
    2 a = []
    3 print(id(a))

    >>> test()
    990348293256

    >>> test()
    990355193096

    >>> test()
    990352013960
    ```
    XYxe
        3
    XYxe  
       2017-06-18 15:15:54 +08:00   ❤️ 2
    因为 CPython 中 list 有一个对象池:
    定义: https://github.com/python/cpython/blob/3.6/Objects/listobject.c#L105-L109
    使用: https://github.com/python/cpython/blob/3.6/Objects/listobject.c#L155-L158
    放回: https://github.com/python/cpython/blob/3.6/Objects/listobject.c#L330-L331

    所以每次执行 f 以后都会使用对象池创建一个对象,然后在执行结束以后再将对象放回到对象池:

    >>> f() # 创建第一个 list,执行结束后放回对象池
    1972051153672
    >>> b = [1,2,3] #创建第二个 list, 从对象池中取出最新放入的对象并使用,使用和第一个 list 相同的内存
    # 如果在这里输出 b 的 id 会发现和上面是一样的
    >>> f() # 创建第三个 list,使用新的内存
    1972041661768 # 结果不一样
    >>> del b # 放回第二个 list
    >>> f() # 创建第四个 list,使用和第一、二个 list 相同的内存
    1972051153672
    >>> c = 1 # 创建一个 int 对象
    >>> f() # 创建第五个 list,和第四个 id 相同,说明 int 不影响 list 的内存池
    1972051153672
    >>> del c
    >>> f() # 同样不影响
    1972051153672
    21grams
        4
    21grams  
       2017-06-18 17:39:14 +08:00
    文档上不是写的很清楚吗? 你这个明显是 non-overlapping lifetimes:
    id(object)
    Return the “ identity ” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5241 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 01:23 · PVG 09:23 · LAX 18:23 · JFK 21:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.