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

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

问题描述

在 Python 中将可变对象设置为函数参数的默认值是一个常见的错误.下面是从 David Goodger 撰写的这篇优秀文章 中摘取的示例:

<预><代码>>>>def bad_append(new_item, a_list=[]):a_list.append(new_item)返回列表>>>打印 bad_append('one')['一']>>>打印 bad_append('两个')['一二']

为什么会发生这种情况的解释是这里.

现在我的问题是:这种语法有很好的用例吗?

我的意思是,如果遇到它的每个人都犯同样的错误,调试它,理解问题,然后试图避免它,这样的语法有什么用?

解决方案

您可以使用它来缓存函数调用之间的值:

def get_from_cache(name, cache={}):如果名称在缓存中:返回缓存[名称]缓存 [名称] = 结果 = 昂贵的计算()返回结果

但通常这种事情最好用一个类来完成,因为你可以有额外的属性来清除缓存等.

It is a common mistake in Python 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']

The explanation why this happens is 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 cache[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天全站免登陆