为什么一个值改变了,而第二个值却没有改变? [英] why did one value change but the second value did not?

查看:71
本文介绍了为什么一个值改变了,而第二个值却没有改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

  1. 如果对象是mutable->,则只需使用新变量指向同一对象
  2. 如果对象是immutable->,则将新对象分配给新变量.
  1. If an object is mutable -> you will just point to the same object with your new variable
  2. 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 immutable int=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 variable c.

有很多关于对象是可变对象的文章,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆