I'm really struggling to understand how this behavior is emerging. I've boiled it down to as small an example as possible which still produces the undesired effect.
- I initialise an instance of a class, whose initiator specificies that if an optional argument is not passed, it should be an empty list.
- I then add some data via a method on the class which should be acting as an instance method.
- I create a new instance of the same class, again without passing a variable to the initiator, but this time the variable is populated as if by magic.
Code:
class Demo:
def __init__(self, x=[]):
self._x = x
print x
def add_x(self, data):
self._x.append(data)
for x in range(0, 5):
obj = Demo()
obj.add_x([1, 2])
Output:
[]
[[1, 2]]
[[1, 2], [1, 2]]
[[1, 2], [1, 2], [1, 2]]
[[1, 2], [1, 2], [1, 2], [1, 2]]
What am I missing?