Python:函数中的默认列表 [英] Python: Default list in function

查看:91
本文介绍了Python:函数中的默认列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

it says as follows: when default values are given, they are created at the time the def statement is executed, not when the function is called. But my question is for the following example:

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)之后,

As the first time definition executed, lst is point to None But after the function call append_if_even(2),


  • 不要首先指向[2],因为在lst.append(x)之​​后不再指向None吗?

  • 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?

推荐答案


首先不要指向[2],因为在lst.append(x)之​​后lst不再指向None了?为什么下一次执行仍然使lst指向无?

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 = [],如果lst是其他lst 构造。虽然该函数的默认参数在编译时仅评估一次,但是每次执行该函数时都会评估该函数中的代码。因此,每次执行函数时都不会传递 lst 的值,它将以默认值 None 开头,然后然后在执行该函数的第一行时立即用一个 new 空列表替换。

That is exactly what you prevent by using the lst=None, lst = [] if lst is None else lst construction. While the default arguments for the function are evaluated only once at compile time, the code within the function is evaluated each time the function is executed. So each time you execute the function without passing a value for lst, it will start with the default value of None and then immediately be replaced by a new empty list when the first line of the function is executed.

如果您要定义的函数类似

If you instead were to define the function like this:

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

然后它将像您一样描述。对于每次运行该函数, lst 的默认值为 same 列表(最初为空),并且传递给该函数的每个偶数将

Then it would act as you describe. The default value for lst will be the same list (initially empty) for every run of the function, and each even number passed to the function will be added to one growing list.

有关更多信息,请参见最小惊讶和可变默认参数

For more information, see "Least Astonishment" and the Mutable Default Argument.

这篇关于Python:函数中的默认列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆