了解Python中的可变性 [英] Understanding mutability in Python
问题描述
我有以下代码段:
a = [1,2,3]
b = a
b = [4,5,6] # a doesnt change
和这个:
a = [1,2,3]
b = a
b[0] = 5 # a also changes
b
的初始化如何决定a
的可变性?
How is b
's initialization playing a part in deciding the mutability of a
?
推荐答案
创建列表并将其分配给变量时,例如
When you create a list and assign it to a variable, like
a = [1, 2, 3]
您创建一个对象,变量a包含对该对象的引用.当你做
You create an object, and the variable a holds a reference to that object. When you do
b = a
您在b中分配了相同的引用,因此a和b现在都指向您的列表.因此,当您执行
You assign the same reference in b, so now both a and b point to your list. So when you execute
b[0] = 5
您更改了同一列表.
您可以通过使用id()函数看到此操作,该函数返回对象的内存地址:
You can see this in action by using the id() function, which returns the memory address of the object:
>>> a = [1, 2, 3]
>>> b = a
>>> id(a), id(b)
(140454191340720, 140454191340720)
它们是相同的.关键是,a和b本身不是列表,它们指向列表.
They are identical. The point is, a and b are not lists themselves, they point to a list.
当您执行以下操作时:
a = [1, 2, 3]
b = a
b = [2, 3, 4]
您首先为b分配了指向它所指向的列表的引用,然后又为其分配了新引用.
You first assigned to b a reference to the list that a points to, but then you assign a new reference to it.
顺便说一句,当您按照以下方式操作时,这可能会在后面咬住您
By the way, this can bite you in the behind when you do something along the lines of
def foo (a=[]):
a.append(42)
return a
由于参数a在每次调用时都指向相同的列表,因此,如果您在没有参数的情况下调用此函数5次,则该列表将包含5x 42:
since the argument a points to the same list on every invocation, if you call this function 5 times without arguments, the list will contain 5x 42:
foo(); foo(); foo(); foo();
print(foo())
>>> [42, 42, 42, 42]
这篇关于了解Python中的可变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!