首先要了解setEqual 方法为什么行不通:你需要知道how identifiers work。 (阅读该链接应该很有帮助。)对于可能有太多术语的快速概述:在您的函数中,参数 restore 绑定到一个对象,您只是将该标识符与 = 运算符重新绑定.下面是一些将标识符 restore 绑定到事物的示例。
# Bind the identifier `restore` to the number object 1.
restore = 1
# Bind the identifier `restore` to the string object 'Some string.'
# The original object that `restore` was bound to is unaffected.
restore = 'Some string.'
所以,在你的函数中,当你说:
restore = []
您实际上是将还原绑定到您正在创建的新列表对象。因为 Python 具有函数局部范围,所以您的示例中的 restore 将函数局部标识符 restore 绑定到新列表。这不会更改您作为还原传递给setEqual 的任何内容。例如,
test_variable = 1
setEqual(test_variable, [1, 2, 3, 4])
# Passes, because the identifier test_variable
# CAN'T be rebound within this scope from setEqual.
assert test_variable == 1
简化一点,您只能在当前执行的范围内绑定标识符——您永远不能编写像def set_foo_to_bar(foo, bar) 这样影响该函数之外的范围的函数。正如@Ignacio 所说,您可以使用诸如复制功能之类的东西来重新绑定当前范围内的标识符:
original = [1, 2, 3, 4]
backup = list(original) # Make a shallow copy of the original.
backup.remove(3)
assert original == [1, 2, 3, 4] # It's okay!