gpt4 book ai didi

python - 为什么 "mutable default argument fix"语法这么难看,python 新手问

转载 作者:IT老高 更新时间:2023-10-28 22:12:34 25 4
gpt4 key购买 nike

现在关注 my series of "python newbie questions"并基于 another question .

特权

转到 http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables并向下滚动到“默认参数值”。在那里您可以找到以下内容:

def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list

def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list

甚至还有一个 "Important warning" on python.org用这个完全相同的例子,并不是真的说它“更好”。

一种说法

所以,这里的问题是:为什么在一个已知问题上的 “好”语法promotes "elegant syntax" and "easy-to-use" 的编程语言中那样丑陋? ?

编辑:

另一种说法

我不是在问 why or how it happens (感谢 Mark 提供的链接)。

我在问为什么没有更简单的语言内置替代方法

我认为更好的方法可能是能够在 def 本身中执行某些操作,其中 name 参数将附加到 中的“本地”或"new" def,可变对象。比如:

def better_append(new_item, a_list=immutable([])):
a_list.append(new_item)
return a_list

我确信有人可以提供更好的语法,但我也猜测必须有一个很好的解释来解释为什么没有这样做。

最佳答案

这称为“可变默认陷阱”。见:http://www.ferg.org/projects/python_gotchas.html#contents_item_6

基本上,a_list 是在第一次解释程序时初始化的,而不是在每次调用函数时初始化(正如您可能对其他语言所期望的那样)。因此,您不会在每次调用该函数时都获得一个新列表,而是重复使用同一个列表。

我想这个问题的答案是,如果你想在列表中附加一些东西,就去做吧,不要创建一个函数来做它。

这个:

>>> my_list = []
>>> my_list.append(1)

比:

更清晰易读
>>> my_list = my_append(1)

在实际情况下,如果您需要这种行为,您可能会创建自己的类,该类具有管理其内部列表的方法。

关于python - 为什么 "mutable default argument fix"语法这么难看,python 新手问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2639915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com