Python的不变性 [英] Immutability in Python
问题描述
我试图了解不变性如何在python中工作.由于字符串在python中是不可变的,因此我期望每次执行字符串操作时id都会更改,但它不能按预期工作. 例子: t上的最后一个操作不会更改其id.有什么想法吗?
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?
推荐答案
我在不同的单元格[memory containing variables (I will not go to the bit level)]
中有一排苹果,其中有些是空的[cells containing garbage / empty value]
.
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]
.
我拿出一个.它在单元格3 [logical address = 3]
中.
I took one out. It was in cell 3 [logical address = 3]
.
我将其涂成蓝色(在我使用未来的技术对其进行克隆以进行不变性演示之后).[committed an operation on it, same could go for addition for integers]
.
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]
.
我看了看它放在哪里,尽管第4单元是空闲的,但第3单元也是(因为这里不再有原始"苹果了)!所以我把它放回单元格3 [and although we get a "new" apple, it has the same address]
.
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]
.
t
也一样(请注意,id
是CPython中变量的内存地址),但是由于我们在这里谈论的是苹果链"(字符串是由字符序列组成的,所以考虑必须要继续执行序列的空间量,因此,如果我的内存看起来像(_
代表任意垃圾数据,'^'代表空间)
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
,我想将字符串更改为"Hello you"
,我可能会考虑使用可用空间:
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
但是如果我想将字符串更改为"Hello world!"
,我将不得不在其他地方寻找长度为"Hello world!"
的可用空间(我们可能会在"BOOM"
之后使用它,这很可能在垃圾回收中)收集的环境,看看您的ID有何不同):
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
这篇关于Python的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!