为什么在 __exit__ 函数中更改引用不起作用?

Why does not changing reference work in __exit__ function?

import copy
class Atomic:
    def __init__(self, mutable, Shallow_copy = True):
        self.original = mutable
        self.copy = copy.copy if Shallow_copy else copy.deepcopy

    def __enter__(self):
        self.modified = self.copy(self.original)
        return self.modified
    
    
    def __exit__(self, exc_type, exc_value, exc_tb):
        if exc_type is None:
           self.original[:] = self.modified

所以我在一本书中看到了这段代码,它应该创建一个上下文管理器来帮助您自动更改列表。如果出现异常,将应用 none 的更改。否则他们都会。例如:

try:       
    with Atomic(example_list) as atomic:
        atomic.append(5)
        atomic.pop(-2)
        atomic[3] = 6
except Exception as err:
    print(err)

像这样一切正常。我不明白的是 exit:

的最后一行
self.original[:] = self.modified

我知道它不会更改引用,而是在不更改引用的情况下更改原始列表中的值。但是为什么这个不起作用:

self.original = self.modified

它将原始列表的引用更改为修改后的列表。所以它应该指的是被修改的列表。但是当你 运行 这样的代码(没有切片)时它不起作用。为什么?

假设您没有进行就地复制。现在 self.original 指的是与以前不同的 list 对象。在运行这段代码

之后
x = [1,2,3]

y = Atomic(x)

with y as atomic:
    atomic.append(5)
    atomic.pop(-2)
    atomic[2] = 6  # No error, so the atomic operation succeeds

您不再有 xy.original 引用同一个列表; x == [1,2,3],但 y.original == [1,2,6].


或者您不知道 x[:] = y 实际上制作了就地副本? x = y 只是让 x 引用 y 所指的任何内容,失去对之前 x 所引用的任何内容的引用。 x[:] = y 更像是

for i in range(len(x)):
    x[i] = y[i]

如果你赋值时不带[:],你会在Atomic对象中改变一个link给这个可变对象,但不会影响原来的可变变量