python-3.x - python : Default list in function

标签 python-3.x default-arguments

来自 Summerfield 的 Python3 编程:

内容如下: 当给出默认值时,它们是在执行 def 语句时创建的,而不是在调用函数时创建的。 但我的问题是针对以下示例:

def append_if_even(x, lst =None):
    lst = [] if lst is None else lst
    if x % 2 ==0:
        lst.append(x)
    return lst

作为第一次执行的定义,lst 指向 None 但是在函数调用 append_if_even(2) 之后,

  • 不应该指向 [2],因为在 lst.append(x) 之后不再指向 None 吗?

  • 为什么下一次执行还是让lst指向none?

  • 这个函数调用 append_if_even(2) 中到底发生了什么?

最佳答案

Shouldn't lst point to [2], since after lst.append(x) lst not point to None anymore? Why the next execution still make lst point to none?

这正是您通过使用 lst=None, lst = [] if lst is None else lst 构造所阻止的。虽然函数的默认参数仅在编译时计算一次,但每次执行函数时都会计算函数内的代码。因此,每次您在不为 lst 传递值的情况下执行函数时,它将以默认值 None 开始,然后立即被替换为 new 执行第一行函数时为空列表。

如果您改为像这样定义函数:

def append_if_even(x, lst=[]):
    if x % 2 ==0:
        lst.append(x)
    return lst

然后它就会像你描述的那样行动。 lst 的默认值将是函数每次运行的相同列表(最初为空),传递给函数的每个偶数都将添加到一个不断增长的列表中.

有关详细信息,请参阅 "Least Astonishment" and the Mutable Default Argument .

关于python-3.x - python : Default list in function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43255481/

相关文章:

c++ - 具有一个默认参数和一个变量参数的C++构造函数

c++ - std::可选与默认参数

函数重载中的 C++ 默认参数评估一次还是每次?

php - PHP 是否有 "named parameters"以便可以省略前面的参数并可以写入后面的参数?

Python GTK3继承

python-3.x - 属性错误 : 'DataFrame' object has no attribute 'droplevel' in pandas

python - 如何使用 imblearn 和 SMOTE 生成分类合成样本?

python-3.x - 类型错误 : ufunc 'isnan' not supported for the input types, - seaborn 热图

python-3.x - 对于每一行,如果行值与条件匹配,则添加列名称以在新列中列出

c++ - Lambda 函数作为构造函数中 std::function 的默认参数