Python 中的可变默认方法参数 [英] Mutable Default Method Arguments In Python

查看:66
本文介绍了Python 中的可变默认方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
“最少惊讶”在 Python 中:可变默认参数

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

def status(self, options=[]):

PyCharm 希望它看起来像:

def status(self, options=None):如果不是选项:选项 = []

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

解决方案

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

例如以下代码:

def status(options=[]):options.append('new_option')退货选项打印状态()打印状态()打印状态()

将打印:

['new_option']['new_option', 'new_option']['new_option', 'new_option', 'new_option']

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

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I am using the Python IDE PyCharm and something that is have by default is it will showing warning when I have a mutbale type as a default value. For example, when I have this:

def status(self, options=[]):

PyCharm wants it to looks like:

def status(self, options=None):
    if not options: options = []

My question is whether or not this is a standard way of doing things in the Python community or is this just the way PyCharm thinks it should be done? Are there any disadvantages of having mutable data type as defaults method arguments?

解决方案

This is the right way to do it because the same mutable object is used every time you call the same method. If the mutable object is changed afterwards, then the default value won't probably be what it was intended to be.

For example, the following code:

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

print status()
print status()
print status()

will print:

['new_option']
['new_option', 'new_option']
['new_option', 'new_option', 'new_option']

which, as I said above, probably isn't what you're looking for.

这篇关于Python 中的可变默认方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆