我有一个将列表作为参数的 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/