Why does the following:
class A(object):
def __init__(self, var=[]):
self._var = var
print 'var = %s %s' % (var, id(var))
a1 = A()
a1._var.append('one')
a2 = A()
result in:
var = [] 182897439952
var = ['one'] 182897439952
I don’t understand why it is not using a new instance of a list when using optional keyword arguments, can anyone explain this?
The empty list in your function definition is created once, at the time the function itself is created. It isn’t created every time the function is called.
If you want a new one each time, do this: