简体   繁体   中英

Immutability in Python

I trying to understand how the immutability works in python. Since string are immutable in python, I was expecting the id to change every time I perform a string operation but it doesn't work as expected. example: The last operation on t doesn't change its id. Any ideas why?

屏幕截图的操作

I had a row of apples in different cells [memory containing variables (I will not go to the bit level)] , of which some were empty [cells containing garbage / empty value] .

I took one out. It was in cell 3 [logical address = 3] .

I painted it blue (after I cloned it using future tech, for immutability demonstration) [committed an operation on it, same could go for addition for integers] .

I looked where to put it, and although cell 4 was free, cell 3 was also (because the "original" apple is not here anymore)! So I put it back in cell 3 [and although we get a "new" apple, it has the same address] .


Same goes for your t (note that id is the memory address of the variable in CPython), but since we are talking about "chains of apples" here (strings are made of a characters sequence, we have to consider the amount of space we have to continue the sequence, so if I had my memory looking like ( _ stands for arbitrary garbage data, '^' for space)

H e l l o _ _ _ _ _ B O O M
^ string pointer points here

and I wanted to change the string to "Hello you" , I might consider using the free space:

H e l l o ^ y o u _ B O O M
^ string pointer points here

But if I want to change the string to "Hello world!" , I would have to look for free space in the length of "Hello world!" somewhere else (we might have it right after "BOOM" , which is probable in a garbage collected environment, look at how your IDs differs):

H e l l o ^ y o u _ B O O M _ H e l l o ^ w o r l d ! _ G A R B A G E
                              ^ string pointer points here

Ids of objects can be reused, as long as the original object is no longer present. This is not specific to strings, but to all Python types. For the simplest example, you can examine the id of a simple object :

>>> print id(object())
140437485756544
>>> print id(object())
140437485756544

However, if we retain a reference to the previous object, the id will not be reused:

>>> a = object()
>>> id(a)
140437485756544
>>> b = object()
>>> id(b)
140437485756560

You can reproduce the same behavior in your tests with strings by appending the intermediate results (values in t ) to a list.

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