简体   繁体   English

为什么具有相同值的可变对象在Python中具有不同的ID

[英]why mutable objects having same value have different id in Python

Thank you for your valuable time, I have just started learning Python. 感谢您的宝贵时间,我才刚刚开始学习Python。 I came across Mutable and Immutable objects. 我遇到了Mutable和Immutable对象。 As far as I know mutable objects can be changed after their creation. 据我所知,可变对象在创建后可以更改。

a = [1,2,3]
print(id(a))
45809352
a = [3,2,1]
print(id(a))
52402312

Then why id of the same list "a" gets changed when its values are changed. 那么,为什么相同列表“ a”的id的值在更改时也会更改。

your interpretation is incorrect. 您的解释不正确。

When you assign a new list to a , you change its reference. 当你分配一个新的lista ,你改变它的参考。

On the other hand you could do: 另一方面,您可以执行以下操作:

a[:] = [3,2,1]

and then the reference would not change. 然后参考不会改变。

mutable means that the content of the object is changed. 可变意味着对象的内容已更改。 for example a.append(4) actually make a equal to [1, 2, 3, 4] , while on the contrary, appending to a string (which is immutable) does not change it, it creates a new one. 例如a.append(4)实际上使a等于[1, 2, 3, 4]而与此相反,附加到字符串(这是不可变的)不改变它,它创建一个新的。

However, when you re-assign, you create a new object and assign it to a , you don't alter the existing content of a . 但是,当您重新分配,创建一个新的对象,并将其分配给a ,你不改变现有内容的a The previous content is lost (unless refered-to by some other variable) 先前的内容丢失(除非被其他变量引用)

If you change a list, its id doesn't change. 如果更改列表,则其ID不会更改。 But you may do things that instead create a new list, and then it will also have a new id. 但是您可以做一些事情来创建一个新列表,然后它也将具有一个新的ID。

Eg, 例如,

>>> l=[]
>>> id(l)
140228658969920
>>> l.append(3)  # Changes l
>>> l
[3]
>>> id(l)
140228658969920  # Same ID
>>> l = l + [4]  # Computes a new list that is the result of l + [4], assigns that
>>> l
[3, 4]
>>> id(l)
140228658977608  # ID changed

When you do 当你做

a = [3, 2, 1]
  1. You unlink the list of [1, 2, 3] from variable a . 您从变量a取消链接[1、2、3]的列表。
  2. Create a new list [3, 2, 1] then assign it to a variable. 创建一个新的列表[3,2,1]然后将其分配给a变量。

Being immutable doesn't mean you assign a new object, it means your original object can be changed "in place" for example via .append() 不可变并不意味着您分配了一个新对象,这意味着可以通过“ .append() ”将原始对象“就地”更改。

>>> my_list = [1,2,3]
>>> id(my_list)
140532335329544
>>> my_list.append(5)
>>> id(my_list)
140532335329544
>>> my_list[3] = 4
>>> my_list
[1, 2, 3, 4]
>>> id(my_list)
140532335329544

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM