为什么 python 在将空列表作为函数的默认参数时显示此行为?

Why does python show this behaviour when having empty list as default argument to a function?

>>> def fun(l=[]):
...     l.append(1)
...     print(l)
... 
>>> fun()
[1]
>>> fun()
[1, 1]
>>> fun([])
[1]
>>> fun()
[1, 1, 1]
>>> 

第二个输出符合预期,解释为 - "A new list is created once when the function is defined, and the same list is used in each successive call."(来源:https://docs.python-guide.org/writing/gotchas/)。
但是当一个空列表作为参数显式传递时,函数的列表应该重置为 [],最后输出应该是 [1, 1] 而不是 [1, 1, 1].

来自同一文档。

Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.

要确认这一点,您可以打印默认参数的 id。默认参数对函数的所有未来调用使用相同的列表对象。但是 fun([]) 将一个新的列表对象传递给 l 因此不使用默认参数的值

>>> def fun(l=[]):
...     l.append(1)
...     print(l, f"id={id(l)}")
... 

>>> fun()
[1] id=4330135048
>>> fun()
[1, 1] id=4330135048
>>> fun([])
[1] id=4330135944
>>> fun()
[1, 1, 1] id=4330135048

文档说“Python 的默认参数在定义函数时计算一次,而不是每次调用函数时计算”。是的。正如我从文档中了解到的那样,一旦定义了函数,列表也会创建并存储值,但在您调用函数的情况下,它将 return 包含列表的已定义函数的值。 当您调用 func([]) 时,您将空列表作为参数传递,该列表已经定义并存储了列表的值。它 return 是当前值,但不会再次存储该值并重置前一个值。因此,当您再次调用 func() 时,它将 return 已存储的列表项。