为什么“可变默认参数修复"为何?语法是如此丑陋,问python newbie [英] Why the "mutable default argument fix" syntax is so ugly, asks python newbie

查看:107
本文介绍了为什么“可变默认参数修复"为何?语法是如此丑陋,问python newbie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在跟随,并基于

Now following my series of "python newbie questions" and based on another question.

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

Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to "Default Parameter Values". There you can find the following:

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

在python.org上甚至还有一个重要警告" 在同样的示例中,您并没有真正说它更好".

There's even an "Important warning" on python.org with this very same example, tho not really saying it's "better".

因此,这里的问题是:为什么在已知问题上的好"语法像在?

So, question here is: why is the "good" syntax over a known issue ugly like that in a programming language that promotes "elegant syntax" and "easy-to-use"?

我不是在问 为什么或如何发生 (感谢Mark的链接).

I'm not asking why or how it happens (thanks Mark for the link).

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

我认为一种更好的方法可能是在def本身中做一些事情,其中​​name参数将附加到def可变对象内的本地"或新".像这样:

I think a better way would probably being able to do something in the def itself, in which the name argument would be attached to a "local", or "new" within the def, mutable object. Something like:

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

我确定有人可以提供更好的语法,但是我也猜想为什么没有做到这一点必须有一个很好的解释.

I'm sure someone can come with a better syntax, but I'm also guessing there must be a very good explanation to why this hasn't been done.

推荐答案

在执行def语句时会评估默认参数,这可能是最合理的方法:通常是所需要的.如果不是这种情况,那么当环境稍有变化时,可能会导致令人困惑的结果.

Default arguments are evaluated at the time the def statement is executed, which is the probably the most reasonable approach: it is often what is wanted. If it wasn't the case, it could cause confusing results when the environment changes a little.

用魔术local方法或类似方法进行区分远非理想. Python试图使事情变得平淡无奇,目前的样板文件没有明显,清晰的替代品,而并没有弄乱Python当前具有的相当一致的语义.

Differentiating with a magic local method or something like that is far from ideal. Python tries to make things pretty plain and there is no obvious, clear replacement for the current boilerplate that doesn't resort to messing with the rather consistent semantics Python currently has.

这篇关于为什么“可变默认参数修复"为何?语法是如此丑陋,问python newbie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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