python - 设置应该是 Python 中列表的参数的默认值的最佳实践?

标签 python default-value pylint

我有一个将列表作为参数的 Python 函数。如果我将参数的默认值设置为这样的空列表:

def func(items=[]):
    print items

Pylint 会告诉我“危险的默认值 [] 作为参数”。所以我想知道这里的最佳做法是什么?

最佳答案

使用 None 作为默认值:

def func(items=None):
    if items is None:
        items = []
    print items

可变默认参数的问题是它将在函数的所有调用之间共享——参见 relevant section of the Python tutorial 中的“重要警告”。 .

关于python - 设置应该是 Python 中列表的参数的默认值的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526465/

相关文章:

mysql - 在 CakePHP 中更新时重置为 MySQL DEFAULT 值

Android CheckBoxPreference 默认值

python - 是否可以在忽略 "# pylint: disable="指令的情况下运行 pylint?

jquery - 如何在具有 defaultValue 的可选字段上使用 jQuery Validator 自定义方法?

CMake - 检查是否安装了 Pylint

python - pylint_django 抛出异常

python - 在 linux 上将 web.py 作为服务运行

python - 我一直收到一个名为 'int' 的错误,对象没有属性 'replace'

Python mysql.connector 模块,将数据传递到字符串 VALUES %s

python - 访问 pandas 数据框列中列表中字典的值