程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The results obtained by calling the method multiple times in python are inconsistent with expectations

編輯:Python

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]
['@']
['@']
['@']

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved