Skip to main content
 首页 » 编程设计

python之无法理解为什么当你重复调用同一个函数时 python 不重新使用参数

2025年05月04日11cmt

我正在看一个关于 python 的教程,它使用了这个例子:

def add_spam(menu=[]): 
    menu.append("spam") 
    return menu 

如果您重复调用 add_spam(),则菜单列表的大小会增加。这对我来说是新的,因为我来自 C# 背景。但是好吧,很公平。

为了解决这个问题,它说您应该将菜单参数设置为 None 但我不明白为什么会这样。这是他们使用的代码:

def add_spam(menu=None): 
    if menu is None: 
        menu = [] 
    menu.append('spam') 
    return menu 

如果你第一次调用它,虽然 menu 将被设置为 [],而第二次肯定如果它像第一个例子中那样“记住”参数,那么 menu 将是 [],因此它只会与第一个示例一样,将垃圾邮件附加到列表中。

除了你应该使用不可变类型之外,该视频忽略了任何解释,所以我无法理解它是如何工作的。

编辑因为我还是不明白:

我看到的是该函数捕获变量,因此它接受 menu=[] 并将其 secret 存储在某处,想象一个名为 _menu 的私有(private)变量,这样如果您再次调用它,它就不会重新计算它只是继续使用 _menu,因此它会增长。

在第二个例子中,我不明白为什么它不简单地采用 menu=None 并将 that secret 存储为 _menu,所以 _menu = None 然后当你调用第二个函数时,它设置 _menu=[] 并完全按照第一个示例继续并增长。

None 是不可变的事实似乎与我无关,因为你没有做 None=[] 你正在做 menu=[] 所以 menu 不再是以前的样子,变成 [] 而你可以随意修改。

除非它是一些硬编码的功能,如果你放 None 它不会执行复制行为,那么我不明白两者之间的区别。

请您参考如下方法:

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).

https://docs.python-guide.org/writing/gotchas/

来自 Python 的文档,一些更详细的信息:

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.

https://docs.python.org/3/reference/compound_stmts.html#function-definitions

列表是可变对象,而 None 是不可变的,因此您会看到这种行为。