假设我将两个变量分配给整数:
a = 1
b = 2
现在,我将a
分配给b
:
a = b
按预期的a == 2
,因为a
已设置为b
的内存地址。
但实际上不是。如果我这样做
b += 1
a
仍然等于2
。为什么a
不指向b
?
答案 0 :(得分:3)
示例中的行为如下
In [1]: a = 1
In [2]: b = 2
In [3]: a = b
In [4]: b+=1
In [5]: b
Out[5]: 3
In [6]: a
Out[6]: 2
在该示例中,当您执行a=b
时,a和b都指向相同的引用,但是当您b += 1
时,将1加到b的操作将创建一个新的整数值{ b和b的{1}}指向该值,但是a仍指向旧值3
请注意,尝试对可变类型(例如列表)进行操作的方式与您所要执行的操作一样,只是会遇到整数
2
现在这里发生了什么?我们更改了In [1]: a = [1]
In [2]: b = [2]
In [3]: a = b
In [4]: b.append(2)
In [5]: a
Out[5]: [2, 2]
In [6]: b
Out[6]: [2, 2]
In [7]: b += [3, 4];
In [8]: b
Out[8]: [2, 2, 3, 4]
In [9]: a
Out[9]: [2, 2, 3, 4]
,但也更改了b
,这是因为a
或列表的更新发生了append
,并且因为in-place
指向了{{1 }}最终都得到更新!
a
运算符的情况由类的b
方法定义。对于+=
-s,所有__iadd__
方法都返回一个新的int实例。对于int
-s __iXXX__
进行list
,因此变量始终指向同一对象。
因此,甚至可以使整数表现为列表,例如here由@imposeren提供
答案 1 :(得分:0)
python中的变量是引用。很少有引用指向不可变的对象(例如字符串,整数等),而列表和集合是可变的。
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
# Consider two variables x & y with integers 23 and 46. They have immutable references
# Meaning, if y=x, it doesn't mean y will change whenever x is updated.
>>> x=23
>>> print (x)
23
>>> y=46
>>> print (x)
23
>>> print (y)
46
>>> y=x
>>> print (x)
23
>>> print (y)
23
# Let's change the value of x after the assignment
>>> x=99
>>> print (x)
99
# Since it is immutable, the value wont change.
>>> print (y)
23
#Let's consider the mutable reference scenario. a & b are two lists which have mutable references
# Meaning, if b=a, it means b will change whenever a is changed
>>> a = list([11,22,33,87])
>>> print (a)
[11, 22, 33, 87]
>>> b = list([87,53,98,2])
>>> print (b)
[87, 53, 98, 2]
>>> a=b
>>> print (a)
[87, 53, 98, 2]
>>> print (b)
[87, 53, 98, 2]
# Popping the list would alter b
>>> b.pop()
2
>>> print (b)
[87, 53, 98]
# Notice the change in value of a
>>> print (a)
[87, 53, 98]
>>>
答案 2 :(得分:0)