关于python:在这两种情况下,对象的这个属性是如何成为不同的值的?

How is this property of an object a different value in these two cases?

本问题已经有最佳答案,请猛点这里访问。

如何调用列表(Case 1的属性,使print y的输出与Case 2的输出不同?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Case 1: using a list as value
>>> x = ["one","two","three"]
>>> y = x
>>> x[0] ="four"
>>> print x
["four","two","three"]
>>> print y
["four","two","three"]

# Case 2: using an integer as value
>>> x = 3
>>> y = x
>>> x = x + 1
>>> print x
4
>>> print y
3

编辑:

为了证明这种行为与列表是可变的和字符串无关,而不是案例2,可以给出以下案例:

1
2
3
4
5
6
7
>>> x = ["one","two","three"]
>>> y = x
>>> x = x + ["four","five"]
>>> print x
["four","two","three","four","five"]
>>> print y
["four","two","three"]


两个片段之间的关键区别是

1
>>> x[0] ="four"

VS

1
>>> x = x + 1

在第一种情况下,修改现有对象,在第二种情况下创建新对象。所以第一个片段有一个对象和两个名称x和y,引用它,在第二个片段中有两个对象。注意,这与列表的可变性(和int的不可变性)无关,您可以将第二个代码段编写为

1
2
3
x = [1,2,3]
y = x
x = x + [4]

得到基本相同的结果(=两个不同的物体)。