Skip to main content
 首页 » 编程设计

具有默认列表参数的 Python 函数

2025年05月04日10lyj

<分区>

在我的程序中遇到了这种怪事。以下是出现问题的部分片段:

#!/usr/bin python 
def test_func( newList, myList=[] ): 
    for t in newList: 
        for f in t: 
            myList.append(f) 
    return myList 
 
print test_func([[3, 4, 5], [6, 7, 8]]) 
print test_func([[9, 10, 11], [12, 13, 14]]) 

第一次调用该函数时,它产生

[3, 4, 5, 6, 7, 8] 

第二次

[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 

我不知道为什么会这样。 python 函数是静态的,因为它们保留了在后续调用中传递给它们的值,还是我的代码中遗漏了什么?