问题与“最小惊讶”和可变默认参数不同。

我运行这样的代码:

def funtest(L=[]):
    L.append(L)
    return L
print(funtest([2]))
print(funtest([3]))
print(funtest([4]))

实际输出在下面。

[2, [...]]
[3, [...]]
[4, [...]]

I know a very heated discussion about the Mutable Default Arguments in before: Least Astonishment” and the Mutable Default Argument

根据Mutable Default Arguments规则,我认为输出应为:

[2, [...]]
[2,3, [...]]
[2,3,4, [...]]

有人对此有想法吗?谢谢

评论
  • lenim
    lenim 回复

    当您不向函数传递任何参数时,默认参数就会出现

    here you are passing arguments to the function namely [2], [3] and [4] and hence default value is not being used

    in your question you mention that for first print output should be [2, [...]] if you are able to understand that , then next ones are exactly same as default argument never comes in the picture.. just focus on how [2, [...]] came