Python 在使用id()时,[]和list()之间有区别吗?
有人能解释一下吗 为什么id相同,但列表不同Python 在使用id()时,[]和list()之间有区别吗?,python,list,python-internals,Python,List,Python Internals,有人能解释一下吗 为什么id相同,但列表不同 >>> [] is [] False >>> id([]) == id([]) True 列表创建有什么不同吗 >>> id(list()) == id(list()) False >>> id([]) == id([]) True 为什么会这样?我有两个不同的清单。为什么不止一个,或者三个或者更多 >>> [].__repr__ <method-wr
>>> [] is []
False
>>> id([]) == id([])
True
列表创建有什么不同吗
>>> id(list()) == id(list())
False
>>> id([]) == id([])
True
为什么会这样?我有两个不同的清单。为什么不止一个,或者三个或者更多
>>> [].__repr__
<method-wrapper '__repr__' of list object at 0x7fd2be868128>
>>> [].__repr__
<method-wrapper '__repr__' of list object at 0x7fd2be868170>
>>> [].__repr__
<method-wrapper '__repr__' of list object at 0x7fd2be868128>
>>> [].__repr__
<method-wrapper '__repr__' of list object at 0x7fd2be868170>
>>[]报告__
>>>[]报告__
>>>[]报告__
>>>[]报告__
您使用的id()
错误<代码>id([])获取立即丢弃的对象的内存id。毕竟,一旦完成了id()
,就再也没有任何东西引用它了。因此,下次使用id([])
Python时,您会看到一个重新使用内存的机会,瞧,这些地址确实是相同的
然而,这是一个实现细节,一个你不能依赖的细节,并且它不总是能够重用内存地址
请注意,id()
值仅在对象的生存期内是唯一的,请参见:
这是一个整数,保证该对象在其生存期内唯一且恒定两个生命周期不重叠的对象可能具有相同的id()
值。
(我的粗体强调)
id(list())
无法重复使用内存位置可能是由于将堆栈上的当前帧推入调用函数,然后在list()
调用返回时再次弹出该函数而导致的额外堆突变
[]
和list()
都会生成一个新的空列表对象;但是您需要首先创建对这些单独列表的引用(这里是a
和b
):
使用[]时也会发生同样的情况。Python交互式解释器有一个特殊的全局名称,。
,可用于引用生成的最后一个结果:
>>> [].__repr__
<method-wrapper '__repr__' of list object at 0x10e011608>
>>> _
<method-wrapper '__repr__' of list object at 0x10e011608>
您从不创建两个以上的列表;前一个(仍由\uu
引用)和当前一个。如果希望查看更多内存位置,请使用变量添加另一个引用
>>> [].__repr__
<method-wrapper '__repr__' of list object at 0x10e011608>
>>> _
<method-wrapper '__repr__' of list object at 0x10e011608>
>>> [].__repr__ # create a new method
<method-wrapper '__repr__' of list object at 0x10e00cb08>
>>> _ # now _ points to the new method
<method-wrapper '__repr__' of list object at 0x10e00cb08>
>>> [].__repr__ # so the old address can be reused
<method-wrapper '__repr__' of list object at 0x10e011608>