Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
For class
class ValidationResult():
def __init__(self, passed=True, messages=[], stop=False):
self.passed = passed
self.messages = messages
self.stop = stop
running
foo = ValidationResult()
bar = ValidationResult()
foo.messages.append("Foos message")
print foo.messages
print bar.messages
produces
['Foos message']
['Foos message']
yet this
foo = ValidationResult()
bar = ValidationResult(messages=["Bars message"])
foo.messages.append("Foos message")
print foo.messages
print bar.messages
produces
['Foos message']
['Bars message']
I think I've missed the boat on understanding instance attributes here. In the first sample, what I expected was Foos message
to only be applied to foo
. What is the correct way to declare an object attribute only mutable by its instance?
Using Python 2.7.1