简体   繁体   中英

Mutable and immutable objects in python

I am aware that in python, integers from -5 to 256 can have the same ID. However, what are the consequences in the case where two immutable objects have the same ID? How about the consequences when two mutable objects have the same ID?

Thank you.

An id is definitionally unique at a given point in time (only one object can have a given id at once). If you see the same id on two names at the same time, it means it's two names referring to the same object. 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); that's why optimizations like the small int cache you've observed are safe.

When two mutable objects have the same ID, they reference the same memory address.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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