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

def test():
a = []
print(id(a))

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

为什么每次产生的地址值都一样?不是会创建新的地址值吗?
Python中谁能确切的解释一下这是为什么?

5 回复

被垃圾回收之后,还可以重复使用那个地址的。这是 Python 的优化。


我无法理解你的问题。

我一定是遇到了一个假 Python ( 2.7.10 和 3.5.1 ):

<br>&gt;&gt;&gt; def test():<br> 2 a = []<br> 3 print(id(a))<br><br>&gt;&gt;&gt; test()<br>990348293256<br><br>&gt;&gt;&gt; test()<br>990355193096<br><br>&gt;&gt;&gt; test()<br>990352013960<br>

因为 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

文档上不是写的很清楚吗? 你这个明显是 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.

回到顶部