我在Python中遇到了一个奇怪的函数行为:
def test_path(n, tree=[]):
print (n, id(tree), tree)
tree.append(n)
if n < 3:
test_path(n+1, tree)
递归函数的可选参数不会在后续调用中重新初始化:
>>> test_path(0)
(0, 140065391163800, [])
(1, 140065391163800, [0])
(2, 140065391163800, [0, 1])
(3, 140065391163800, [0, 1, 2])
>>> test_path(1)
(1, 140065391163800, [0, 1, 2, 3])
(2, 140065391163800, [0, 1, 2, 3, 1])
(3, 140065391163800, [0, 1, 2, 3, 1, 2])
>>> test_path(1, [])
(1, 140065391262032, [])
(2, 140065391262032, [1])
(3, 140065391262032, [1, 2])
为什么三个对象在未定义的所有调用中是相同的?我做错了什么?