The script contains default parameters,多次調用該方法,The default value was found to carry over from previous results
代碼如下:
def func(a, tes=[]):
tes.append(a)
print(tes)
if __name__ == '__main__':
for i in range(5):
func(i)
func(10, [10])
for x in "test":
func(x)
func(110, [101])
for x in "@@@":
func(x)
輸出結果為:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[10, 10]
[0, 1, 2, 3, 4, 't']
[0, 1, 2, 3, 4, 't', 'e']
[0, 1, 2, 3, 4, 't', 'e', 's']
[0, 1, 2, 3, 4, 't', 'e', 's', 't']
[101, 110]
[0, 1, 2, 3, 4, 't', 'e', 's', 't', '@']
[0, 1, 2, 3, 4, 't', 'e', 's', 't', '@', '@']
[0, 1, 2, 3, 4, 't', 'e', 's', 't', '@', '@', '@']
執行func(10, [10])和func(110, [101])When the result is normal,But an error occurs when traversing
這是因為:
A function's parameter default value will only be initialized once,and reused. When the parameter defaults to a mutable object
時,若函數調用時No parameter value is passed in,then any operation on the default value of the parameter actually operates on the same object.
Modify the default value to be an immutable parameter:
def func(a, tes=None):
tes = []
tes.append(a)
print(tes)
if __name__ == '__main__':
for i in range(5):
func(i)
func(10, [10])
for x in "test":
func(x)
func(110, [101])
for x in "@@@":
func(x)
輸出就正常了:
[0]
[1]
[2]
[3]
[4]
[10]
['t']
['e']
['s']
['t']
[110]
['@']
['@']
['@']