可变默认参数
def append_to(element, to=[]):
to.append(element)
return to
print(append_to(111))
print(append_to(222))
print(append_to(333))
# 实际输出
[111]
[111, 222]
[111, 222, 333]
因为在定义函数的时候,就创建了一个可变对象list, 后续所有操作都是在这一个对象中进行的(dict也不行)
# 正确写法
def append_to(element, to=None):
if to == None:
to = []
to.append(element)
return to