I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
I am noticing the following:
class c:
def __init__(self, data=[]):
self._data=data
a=c()
b=c()
a._data.append(1)
print b._data
[1]
Is this the correct behavior?
Yes, it's correct behavior.
However, from your question, it appears that it's not what you expected.
If you want it to match your expectations, be aware of the following:
Rule 1. Do not use mutable objects as default values.
def anyFunction( arg=[] ):
Will not create a fresh list object. The default list object for arg will be shared all over the place.
Similarly
def anyFunction( arg={} ):
will not create a fresh dict object. This default dict will be shared.
class MyClass( object ):
def __init__( self, arg= None ):
self.myList= [] if arg is None else arg
That's a common way to provide a default argument value that is a fresh, empty list object.
Will never work. is a bit harsh. Won't give you a new empty mutable object on each call, seems a little more balanced. If you know this happens you might actually want to use this behaviour.Always make functions like this then:
def __init__ ( self, data = None ):
if data is None:
data = []
self._data = data
Alternatively you could also use data = data or [], but that prevents the user from passing empty parameters ('', 0, False etc.).
if not data: data = [].data = data or [] works just fine for empty lists being passed. You'd be saying data will be [] or [] so it will look at the first one and see that it evaluates to "false", then it will take the other value.False for example, [] will be used as the value, although you passed False.