有人可以用一种易于理解的方式解释修改与覆盖对象引用吗?这是我的意思的一个例子:
通过修改对象引用:
nested_list = [[]]*3
nested
result:
[[], [], []]
# now let me **modify** the object reference
nested[1].append('zzz')
result:
[['zzz'], ['zzz'], ['zzz']]
通过覆盖对象引用:
nested_list = [[]]*3
nested
result:
[[], [], []]
# now let me **modify** the object reference
nested[1] = ['zzz']
result:
[[], ['zzz'], []]
这是否意味着当使用“append”时,我们仅在使用赋值时修改对象引用,即
nested[1] = ['zzz']
我们要覆盖该值并将nested[1] 分配给新的对象引用吗?这是由“append”方法和赋值之间的根本差异引起的吗?如果是的话有什么区别?
最佳答案
让我们将名称 x
分配给一个空列表,以便更容易推理代码。
在你的第一个例子中
>>> x = []
>>> nested = [x]*3
>>> nested
[[], [], []]
您正在创建一个嵌套
列表,其中包含对x
的三个引用。证据如下:
>>> all(e is x for e in nested)
True
我们只创建了一个空列表x
,这就是原因
nested[0].append('zzz')
nested[1].append('zzz')
nested[2].append('zzz')
和
x.append('zzz')
都是等价的并且附加到内存中的同一个列表:
>>> nested[0].append('zzz')
>>> nested
[['zzz'], ['zzz'], ['zzz']]
>>> nested[1].append('zzz')
>>> nested
[['zzz', 'zzz'], ['zzz', 'zzz'], ['zzz', 'zzz']]
>>> nested[2].append('zzz')
>>> nested
[['zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz']]
>>> x.append('zzz')
>>> nested
[['zzz', 'zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz', 'zzz']]
第二个例子很简单。您创建一个嵌套
列表,该列表最初包含对同一空列表的三个引用。
然后你覆盖nested
的第二个元素(即nested[1]
)通过发出
>>> x = []
>>> nested = [x]*3
>>> nested[1] = ['zzz']
>>> nested
[[], ['zzz'], []]
nested
的第二个元素是一个新列表,与 nested
的第一个和第三个元素无关。
>>> nested[0] is nested[1]
False
>>> nested[2] is nested[1]
False
>>> nested[0] is nested[2]
True
由于您没有修改 nested[0]
和 nested[2]
引用,因此它们仍然持有相同的空列表(在我们的示例中也由名称x
)。
>>> x.append('x')
>>> nested
[['x'], ['zzz'], ['x']]
关于Python - 修改与覆盖对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965902/