对象变动(Mutation)
刚刚发生了什么?我们预期的不是那样!我们期望看到是这样的:
print(foo)
# Output: ['hi']
bar = foo
bar += ['bye']
print(foo)
# Output: ['hi']
你可能预期它表现的不是这样子。你可能希望,当你调用add_to
时,有一个新的列表被创建,就像这样:
def add_to(num, target=[]):
target.append(num)
return target
add_to(1)
# Output: [1]
add_to(2)
# Output: [2]
add_to(3)
# Output: [3]
现在每当你在调用这个函数不传入target
参数的时候,一个新的列表会被创建。举个例子:
add_to(42)
# Output: [42]
add_to(42)
# Output: [42]
add_to(42)