Mutable Default Method Arguments In Python [duplicate]

青春壹個敷衍的年華 提交于 2021-02-20 18:46:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9039191/mutable-default-method-arguments-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!