来自 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/