为元组分配相同的值时,为什么不获得相同的ID? [英] Why don't tuples get the same ID when assigned the same values?

查看:120
本文介绍了为元组分配相同的值时,为什么不获得相同的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行以下步骤时,即使我重新分配了旧值((1,2)),两个元组(ab)都没有保留其原始ID.

When I executed the following steps, both tuples (a and b) haven't retained their original IDs even when I reassigned older values ((1,2)).

>>> a , b = (1,2) , (1,2)
>>> a
(1, 2)
>>> b
(1, 2)
>>> id(a) , id(b)
(80131912, 91541064)
>>> a , b = (3,4) , (3,4)
>>> a
(3, 4)
>>> b
(3, 4)
>>> id(a) , id(b)
(91559048, 91689032)
>>> a , b = (1,2) , (1,2)
>>> a
(1, 2)
>>> b
(1, 2)
>>> id(a) , id(b)
(91556616, 91550408)

但是在以下情况下,两个都恢复了其较早的ID.

But in the following case, both have gotten their older IDs back.

>>> a = (1,2)
>>> b = (1,2)
>>> a , b
((1, 2), (1, 2))
>>> id(a)
88264264
>>> id(b)
88283400
>>> a = (3,4)
>>> b = (3,4)
>>> id(a)
88280008
>>> id(b)
88264328
>>> a = (1,2)
>>> b = (1,2)
>>> id(a)
88264264
>>> id(b)
88283400
>>> a , b
((1, 2), (1, 2))
>>> id(a) , id(b)
(88264264, 88283400)

有人可以解释一下吗?

推荐答案

您创建了新的元组对象.它们具有相同的内容并不意味着它们将成为内存中完全相同的元组对象.

You created new tuple objects. That they have the same contents doesn't mean that they'll be the exact same tuple objects in memory.

不可移植性并不意味着创建相同的将创建相同的 object .您从不会对旧的(1, 2)元组进行突变,而新的(1, 2)元组也不是可变的.

Immutability doesn't mean that creating the same value will create the same object. You never mutated the old (1, 2) tuples, and your new (1, 2) tuples are not mutable either.

CPython确实保留了可重复使用的元组对象的缓存(因此它不必一直创建新的对象,Python在典型程序中会经历很多小的元组),但这是您可以实现的详细信息不依靠.正是由于这个缓存,才再次看到了相同的ID(长度为2的元组)的原因.如果您想了解缓存的方式,请参见如何在CPython中实现元组?已实现.

CPython does keep a cache of re-usable tuple objects (so it doesn't have to create new objects all the time, Python goes through a lot of small tuples during a typical program), but that's an implementation detail you can't rely on. It is this cache that is the reason for the same ids being seen again, for tuples of length two. See How is tuple implemented in CPython? if you want to know how the cache is implemented.

此外,在CPython中,id()是对象的内存位置,并且一旦释放了旧对象,Python便可以自由地重新使用内存位置.这是明确记录的:

Furthermore, in CPython, id() is the memory location of the object, and Python is free to re-use memory locations once old objects have been freed. This is clearly documented:

这是一个整数,可以保证此对象在其生存期内唯一且恒定.具有不重叠生命周期的两个对象可能具有相同的id()值.

总是有可能为新对象看到相同的id()值.有时,这意味着您仍然具有相同的对象(如小整数或元组或某些类型的字符串对象的情况),有时仅仅是解释器重新使用了内存中的相同位置.您永远不要依赖它,这些是出于性能目的并且可能随时更改的实现细节.

It is always possible to see the same id() value for new objects. Sometimes this means you still have the same object (as is the case for small integers or tuples or certain types of string object), sometimes it is just that the interpreter re-used the same location in memory. You should never rely on this, these are implementation details for performance purposes and subject to change.

这篇关于为元组分配相同的值时,为什么不获得相同的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆