gpt4 book ai didi

python - 可变函数参数默认值的好用途?

转载 作者:IT老高 更新时间:2023-10-28 20:28:39 24 4
gpt4 key购买 nike

将可变对象设置为函数中参数的默认值是 Python 中的常见错误。这是取自 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']

发生这种情况的解释是here .

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

我的意思是,如果遇到它的每个人都犯了同样的错误,调试它,理解问题并从那里尝试避免它,那么这种语法有什么用?

最佳答案

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

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

但通常这类事情用类做得更好,因为你可以有额外的属性来清除缓存等。

关于python - 可变函数参数默认值的好用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com