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

2017-06-18 11:37:53 +08:00
 SimbaPeng
def test():
a = []
print(id(a))

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

为什么每次产生的地址值都一样?不是会创建新的地址值吗?
2634 次点击
所在节点    Python
4 条回复
ruoyu0088
2017-06-18 11:46:19 +08:00
被垃圾回收之后,还可以重复使用那个地址的。这是 Python 的优化。
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
2017-06-18 15:15:54 +08:00
因为 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
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.

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

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

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

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

© 2021 V2EX