https://eastlakeside.gitbooks.io/interpy-zh/content/Mutation/
看下面的代码
def add_to(num, target=[]):
target.append(num)
return target
add_to(1)
# Output: [1]
add_to(2)
# Output: [1, 2]
add_to(3)
# Output: [1, 2, 3]
这次又没有达到预期,是列表的可变性在作怪。在Python中当函数被定义时,默认参数只会运算一次,而不是每次被调用时都会重新运算
。
你应该永远不要定义可变类型的默认参数,除非你知道你正在做什么。你应该像这样做:
def add_to(element, target=None):
if target is None:
target = []
target.append(element)
return target
现在每当你在调用这个函数不传入target参数的时候,一个新的列表会被创建。举个例子:
add_to(42)
# Output: [42]
add_to(42)
# Output: [42]
add_to(42)
# Output: [42]