对象变动Mutation
可变(mutable)对象意味着这个对象可以被改动,不可变(immutable)对象意味着对象是常量(constant)
foo = ['hi']
print(foo)
bar = foo
bar += ['bye']
print(foo)
"""
['hi']
['hi', 'bye']
"""
这就是对象可变性的作用,每当你将一个变量赋值给另一个可变类型的变量时,对这个数据的任意变动同时反映到这两个变量上。新变量只不过是另一个变量的一个别名而已。
def add_to(num, target=[]):
target.append(num)
return target
print(add_to(1))
print(add_to(2))
print(add_to(3))
"""
[1]
[1, 2]
[1, 2, 3]
"""
这个也是列表的可变性在作怪。在Python中当函数被定义时,默认参数只会运算一次,而不是每次调用时会重新运算。因此永远不要定义可变类型的默认值,除非知道自己在做什么。
重新定义函数
def add_to(element, target = None):
if target is None:
target =[]
target.append(element)
return target
这样就不会出现上述的情形了。