这里所说的可变对象一般是指list,dict等,首先看现象:
- >>> def function(data = []):
- ... data.append(1)
- ... print data
- ... print type(data)
- ...
- >>> function()
- [1]
- <type 'list'>
- >>> function()
- [1, 1]
- <type 'list'>
- >>>
- >>> (function.func_defaults[0])
- [1, 1]
- >>> id(function.func_defaults[0])
- 3070981484L
- >>> function()
- [1, 1, 1]
- <type 'list'>
- >>> id(function.func_defaults[0])
- 3070981484L
- >>> def a():
- ... print "a executed"
- ... return []
- ...
- >>>
- >>> def b(x=a()):
- ... x.append(5)
- ... print x
- ...
- a executed
- >>> b()
- [5]
- >>> b()
- [5, 5]
- >>> def a():
- ... print "a executed"
- ... return []
- ...
- >>>
- >>> def b(x=a()):
- ... x.append(5)
- ... print x
- ...
- a executed
- >>> b()
- [5]
- >>> b()
- [5, 5]
复制代码
怎么避免这种情况呢?使用None作为占位符,如下:- >>> def instead_function(data=None):
- ... if data is None:
- ... data = []
- ... data.append(1)
- ... print data
- ...
- >>> instead_function()
- [1]
- >>> instead_function()
- [1]