为什么一个值改变了,而第二个值却没有改变? [英] why did one value change but the second value did not?
问题描述
a = [ 1, 2 ]
b = a
a.append(3)
print(b) # shows [ 1 2 3 ] which means b changed
c = 4
d = c
c = 8
print(d) # shows 4 which means d did not change
为什么b改变了,而d没有改变? .append更改了存储在b中的值,但是c = 8并没有更改d中的值
Why did b change, but d did not? the .append changed the value stored in b, but c = 8 did not change the value in d
推荐答案
这完全取决于您分配的对象是mutable
还是immutable
.
It's all about if the object you assign is mutable
or immutable
.
简单地说-可变对象创建后可以更改,不可变对象不能更改.
Simply put - mutable objects can be changed after they are created, immutable objects can't.
考虑到您有一个分配给对象的变量a
,当您将新变量指向a
变量时,有两种可能性:
Considering you have a variable a
that is assigned to an object, when you point a new variable to the a
variable, there are two possibilities:
- 如果对象是
mutable
->,则只需使用新变量指向同一对象 - 如果对象是
immutable
->,则将新对象分配给新变量.
- If an object is
mutable
-> you will just point to the same object with your new variable - If an object is
immutable
-> you will assign a new object to your new variable.
您的第一种情况:
- 首先创建一个列表
a
,它是一个可变对象 - 然后使用第二个变量
b
指向同一列表对象. - 更改值时,只需更改两个变量都指向的可变对象即可.
- First you create a list
a
, which is a mutable object - Then you point with a second variable
b
to the same list object. - When you change value, you just change a mutable object, to which both variables are pointing.
第二种情况:
- 首先,您将变量
c
分配给不可变的int=4
对象. - 然后将其分配给第二个变量
d
. - 接下来,您将为变量
c
分配一个新的不可变的int=8
对象.
- First you assign a variable
c
to an immutableint=4
object. - Then you assign it to the second variable
d
. - And what happens next, is that you assign a new immutable
int=8
object to the variablec
.
There is plenty of articles about what does it mean that an object is mutable, for example: https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747
这篇关于为什么一个值改变了,而第二个值却没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!