Python 3.8 跨多个函数调用的递归函数保存列表?

Python 3.8 recursive function saving list across multiple function calls?

我 运行 在 python 3 上遇到了一些项目问题,因此决定创建较小的版本以了解发生了什么。事实证明,这让我更加困惑。好吧,我写下了那个简单的基于递归的代码:

>> Code

1-  def rec(memory=[], x=2):
2-      print(memory, x)
3-      if x > 0:
4-          memory.append(x)
5-          x -= 1
6-          rec(memory=memory, x=x)
7-      else:
8-          memory=[]
9-          return 0
10- 
11- rec()
11- print("First call done.")
12- rec()

并期待这样的事情:

>> Desired output

[] 2
[2] 1
[2, 1] 0
First call done.
[] 2
[2] 1
[2, 1] 0

但最终收到了:

>> Real output

[] 2
[2] 1
[2, 1] 0
First call done.
[2, 1] 2
[2, 1, 2] 1
[2, 1, 2, 1] 0

有人知道为什么即使我在第 8 行明确告诉它要将内存设置回空列表时 rec() 函数仍保留内存吗?还有...我要怎么做才能不在多个函数调用中保存信息?

在不解释内部工作原理的情况下,您可以这样做:

def rec(memory = [], x = 2):
    print(memory)
    if x:
        memory.append(x)
        x -= 1
        rec(memory = memory, x = x)
    else:
        del memory[:]
        return

rec()
print("First call done.")
rec()

---

[]
[2]
[2, 1]
First call done.
[]
[2]
[2, 1]