具有相同列表的两个变量具有不同的ID .....为什么? [英] Two variables with the same list have different IDs.....why is that?

查看:464
本文介绍了具有相同列表的两个变量具有不同的ID .....为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图了解以下内容

为什么相同列表的Python分配的ID不同?

Why is it that the ID's assigned by Python are different for the same lists?

x = [1, 2, 3]
y = [1, 2, 3]

id(x) != id(y)
True

id(x)
11428848

id(y)
12943768

推荐答案

Python中每个不同的 object 都有其自己的ID.它与内容无关-与描述对象的信息的存储位置有关.存储在不同位置的任何不同对象将具有不同的ID. (它是 有时 ,但不是 始终 ,即该对象.)

Every distinct object in Python has its own ID. It's not related to the contents -- it's related to the location where the information that describes the object is stored. Any distinct object stored in a distinct place will have a distinct id. (It's sometimes, but not always, the memory address of the object.)

这对于了解可变对象(即可以更改的对象,例如列表)尤其重要.如果可以更改对象,则可以创建两个具有相同内容的不同对象.它们将具有不同的ID,并且如果您以后更改一个,则第二个将不会更改.

This is especially important to understand for mutable objects -- that is, objects that can be changed, like lists. If an object can be changed, then you can create two different objects with the same contents. They will have different IDs, and if you change one later, the second will not change.

对于诸如整数和字符串之类的不可变对象,这并不重要,因为内容永远不会改变.即使两个不可变对象具有不同的ID,但如果它们具有相同的内容,它们在本质上也是相同的.

For immutable objects like integers and strings, this is less important, because the contents can never change. Even if two immutable objects have different IDs, they are essentially identical if they have identical contents.

这套想法很深入.您可以将变量名视为分配给ID号的标签,该ID号又可以唯一地标识一个对象.可以使用多个变量名来标记同一对象.观察:

This set of ideas goes pretty deep. You can think of a variable name as a tag assigned to an ID number, which in turn uniquely identifies an object. Multiple variable names can be used to tag the same object. Observe:

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> id(a)
4532949432
>>> id(b)
4533024888

那,您已经发现了.现在让我们创建一个新的变量名称:

That, you've already discovered. Now let's create a new variable name:

>>> c = b
>>> id(c)
4533024888

尚未创建新对象.标记为b的对象现在也标记为c.当我们更改a时会发生什么?

No new object has been created. The object tagged with b is now tagged with c as well. What happens when we change a?

>>> a[1] = 1000
>>> a
[1, 1000, 3]
>>> b
[1, 2, 3]

我们知道,

ab是不同的,因为它们具有不同的ID.因此,更改一个不会影响另一个.但是bc是同一个对象-还记得吗?所以...

a and b are different, as we know because they have different IDs. So a change to one doesn't affect the other. But b and c are the same object -- remember? So...

>>> b[1] = 2000
>>> b
[1, 2000, 3]
>>> c
[1, 2000, 3]

现在,如果我为b分配一个新值,则它不会更改对象本身的任何内容-只是标记它们的方式:

Now, if I assign a new value to b, it doesn't change anything about the objects themselves -- just the way they're tagged:

>>> b = a
>>> a
[1, 1000, 3]
>>> b
[1, 1000, 3]
>>> c
[1, 2000, 3]

这篇关于具有相同列表的两个变量具有不同的ID .....为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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