将可变对象设置为函数中参数的默认值是 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/