Python中的可变默认方法参数

rya*_*zec 3 python pycharm

可能重复:
Python中的"最小惊讶":可变默认参数

我正在使用Python IDE PyCharm,默认情况下它会在我将mutbale类型作为默认值时显示警告.例如,当我有这个:

def status(self, options=[]):
Run Code Online (Sandbox Code Playgroud)

PyCharm希望它看起来像:

def status(self, options=None):
    if not options: options = []
Run Code Online (Sandbox Code Playgroud)

我的问题是,这是否是在Python社区中做事的标准方式,还是这就是PyCharm认为应该这样做的方式?将可变数据类型作为默认方法参数有什么缺点吗?

jco*_*ado 5

这是正确的方法,因为每次调用相同的方法时都会使用相同的可变对象.如果之后更改了可变对象,则默认值可能不是它的预期值.

例如,以下代码:

def status(options=[]):
    options.append('new_option')
    return options

print status()
print status()
print status()
Run Code Online (Sandbox Code Playgroud)

将打印:

['new_option']
['new_option', 'new_option']
['new_option', 'new_option', 'new_option']
Run Code Online (Sandbox Code Playgroud)

正如我上面所说,这可能不是你想要的.