Python中的不变性

New*_*bie 9 python immutability python-2.7

我试图理解不变性在python中是如何工作的.因为字符串在python中是不可变的,所以我希望每次执行字符串操作时都会更改id,但它不能按预期工作.示例:t上的最后一个操作不会更改其ID.有什么想法吗?

屏幕截图的操作

Uri*_*iel 5

我在不同的细胞中有一排苹果[memory containing variables (I will not go to the bit level)],其中一些是空的[cells containing garbage / empty value].

我拿了一个.它在单元格3中[logical address = 3].

我把它画成蓝色(在我用未来的技术克隆它之后,进行不变性演示)[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].


同样适用于你t(请注意这id是CPython中变量的内存地址),但由于我们在这里讨论"苹果链"(字符串是由字符序列组成的,我们必须考虑我们拥有的空间量)继续序列,所以如果我的内存看起来像(_代表任意垃圾数据,'^'代表空间)

H e l l o _ _ _ _ _ B O O M
^ string pointer points here
Run Code Online (Sandbox Code Playgroud)

我想将字符串更改为"Hello you",我可能会考虑使用空闲空间:

H e l l o ^ y o u _ B O O M
^ string pointer points here
Run Code Online (Sandbox Code Playgroud)

但是如果我想要将字符串更改为"Hello world!",我将不得不寻找"Hello world!"其他地方长度的可用空间(我们可能会"BOOM"在垃圾收集环境中找到它,看看你的ID如何不同):

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
Run Code Online (Sandbox Code Playgroud)