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

标签 python default-arguments

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

相关文章:

python - Django 模型 : Inherit from variable abstract base class

python - 如何删除列表列表中的 "\n"(python)

python - 如何通过点击QProgressDialog的取消按钮来取消QProcess?

python - PCA 线拟合聚类算法

c++ - 访问没有对象的私有(private)成员变量

python - 用于匹配名称后跟可选空格的正则表达式,但忽略注释

c++ - 默认参数和参数包之间的交互(GCC 和 clang 不同意)

c++ - 使用 {fmt} 和 source_location 创建基于可变参数模板的日志功能

swift - 将默认参数值发送给函数?

c++ - 提取模板类默认参数