首先要了解的是为什么该setEqual
方法不能工作:你需要知道标识符是如何工作的。(阅读该链接应该很有帮助。)对于可能有太多术语的快速概述:在您的函数中,参数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
Simplifying a bit, you can only bind identifiers in the currently executing scope -- you can never write a function like def set_foo_to_bar(foo, bar)
that affects the scope outside of that function. As @Ignacio says, you can use something like a copy function to rebind the identifier in the current scope:
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!