Good uses for mutable function argument default values?(可变函数参数默认值的好用途?)
问题描述
将可变对象设置为函数中参数的默认值是 Python 中的常见错误.下面是一个示例,取自 David Goodger 的这篇出色的文章:
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.
现在我的问题是:这种语法有很好的用例吗?
我的意思是,如果遇到它的每个人都犯了同样的错误,调试它,理解问题并从那里尝试避免它,那么这种语法有什么用?
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.
这篇关于可变函数参数默认值的好用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可变函数参数默认值的好用途?


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01