现在跟随我的一系列"python新手问题"并基于另一个问题.
转到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
Run Code Online (Sandbox Code Playgroud)
在python.org上甚至还有一个"重要的警告",这个例子非常相同,并不是说它"更好".
所以,这里的问题是:为什么在一个已知问题上的"好"语法比在一个促进"优雅语法"和"易于使用"的编程语言中那样丑陋?
编辑:
我不是在问为什么或如何发生(感谢Mark的链接).
我问为什么没有更简单的替代内置语言.
我认为更好的方法可能是在def自身中做一些事情,其中name参数将附加到def可变对象中的"本地"或"新" .就像是:
def better_append(new_item, a_list=immutable([])):
a_list.append(new_item)
return a_list
Run Code Online (Sandbox Code Playgroud)
我相信有人可以提供更好的语法,但我也猜测必须有一个非常好的解释为什么没有这样做.