对于可变函数参数的默认值好用途? [英] Good uses for mutable function argument default values?

查看:142
本文介绍了对于可变函数参数的默认值好用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个常见的​​错误是设置一个可变对象作为函数参数的默认值。下面是来自这个优秀的写了由David Goodger :

It is a common mistake to set a mutable object as the default value of an argument in a function. Here's an example taken from this excellent write-up by David Goodger:

>>> def bad_append(new_item, a_list=[]):
        a_list.append(new_item)
        return a_list
>>> print bad_append('one')
['one']
>>> print bad_append('two')
['one', 'two']

为什么出现这种情况的解释是<一个href=\"http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values\">here.

而现在我的问题:是否有一个良好的用例此语法结果我的意思是,如果大家谁遇到这让同样的错误,调试它,理解问题和?从上面设法避免它,有什么用是有这样的语法?

And now for my question: Is there a good use-case for this syntax?
I mean, if everybody who encounters it makes the same mistake, debugs it, understands the issue and from thereon tries to avoid it, what use is there for such syntax?

推荐答案

您可以与函数调用使用它的缓存值:

You can use it to cache values between function calls:

def get_from_cache(name, cache={}):
    if name in cache: return name
    cache[name] = result = expensive_calculation()
    return result

但通常那种事情做一个更好的类,你就可以有额外的属性来清除缓存等。

but usually that sort of thing is done better with a class as you can then have additional attributes to clear the cache etc.

这篇关于对于可变函数参数的默认值好用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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