我在不同的牢房里有一排苹果[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
我想将字符串更改为"Hello you"
,我可能会考虑使用可用空间:
H e l l o ^ y o u _ B O O M
^ string pointer points here
但是如果我想将字符串更改为"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