问题
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