相关疑难解决方法(0)

为什么"可变的默认参数修复"语法如此丑陋,请问python newbie

现在跟随我的一系列"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)

我相信有人可以提供更好的语法,但我也猜测必须有一个非常好的解释为什么没有这样做.

python mutable names

28
推荐指数
3
解决办法
2303
查看次数

标签 统计

mutable ×1

names ×1

python ×1