简体   繁体   English

python中的可变和不可变对象

[英]Mutable and immutable objects in python

I am aware that in python, integers from -5 to 256 can have the same ID.我知道在 python 中,从 -5 到 256 的整数可以具有相同的 ID。 However, what are the consequences in the case where two immutable objects have the same ID?但是,如果两个不可变对象具有相同的 ID,会有什么后果呢? How about the consequences when two mutable objects have the same ID?当两个可变对象具有相同的 ID 时,后果如何?

Thank you.谢谢你。

An id is definitionally unique at a given point in time (only one object can have a given id at once). id在给定的时间点定义是唯一的(一次只有一个对象可以具有给定的id )。 If you see the same id on two names at the same time, it means it's two names referring to the same object.如果您同时在两个名称上看到相同的id ,则表示这两个名称指向同一个对象。 There are no "consequences" to this for immutable types like int , because it's impossible to modify the object through either alias ( x = y = 5 aliases both x and y to the same 5 object, but x += 1 is roughly equivalent to x = x + 1 for immutable objects, rebinding x to a new object, 6 , not modifying the 5 object in place);对于像int这样的不可变类型没有“后果”,因为不可能通过任一别名修改对象( x = y = 5xy别名为同一个5对象,但x += 1大致相当于x = x + 1对于不可变对象,将x重新绑定到新对象6 ,而不是在适当的位置修改5对象); that's why optimizations like the small int cache you've observed are safe.这就是为什么像您观察到的小型int缓存这样的优化是安全的。

When two mutable objects have the same ID, they reference the same memory address.当两个可变对象具有相同的 ID 时,它们引用相同的内存地址。

a = 10
b = 10
print(id(a), id(b))

Output:输出:

4355009952 4355009952

The only consequence of two mutable objects having the same ID is changing the value in one object will be reflected on the other.具有相同 ID 的两个可变对象的唯一后果是更改一个对象中的值将反映在另一个对象上。

a = 10
b = a
print(a, b)
print(id(a), id(b))
a = 6
print(a, b)
print(id(a), id(b))

Output:输出:

10 10
4338298272 4338298272
6 10
4338298144 4338298272

Immutable objects having the same is not a consequence as they are immutable具有相同的不可变对象不是结果,因为它们是不可变的

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

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