“为什么"? python数据类型是不可变的 [英] "Why" python data types are immutable
问题描述
为什么(不是怎么做)像int和string这样的python基本数据类型是不可变的.那是因为脚本语言的实现限制.
Why (not how) python primitive data types like int and string are immutable. Is that because of a implementation limitation of scripting language.
作为示例
a = 5;
a = 6;
在第二行(a = 6;)中
而不是创建新的存储位置,为什么不能将第一个存储位置更改为6
in second line(a = 6;) instead of creating a new memory location, why cant it change the first memory location to 6
推荐答案
某些Python数据类型是不可变的,因为Python使用引用/指针语义.
Some Python data types are immutable because Python uses reference/pointer semantics.
这意味着,每当将表达式分配给变量时,实际上并没有将值复制到该变量表示的存储位置,而只是给实际存在该值的存储位置命名.
This means that whenever you assign an expression to a variable, you're not actually copying the value into a memory location denoted by that variable, but you're merely giving a name to the memory location where the value actually exists.
现在,例如,如果字符串是可变的,则会发生这种情况:
Now, if for example strings were mutable, this would happen:
a = "test"
b = a
b[2] = "o"
# Now a would be "tost", oops.
这种行为被认为是不直观的,因此字符串变得不可变.
This behaviour was considered unintuitive, so strings were made immutable.
与整数类似,如果分配新值将更改原始位置,则会发生以下情况:
Similarly for integers, if assigning a new value would change the original location, the following would happen:
a = 5
b = a
b += 5
# a is now 10 :(
这篇关于“为什么"? python数据类型是不可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!