The +=
operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?
class foo:
bar = []
The problem here is, bar
is defined as a class attribute, not an instance variable.
In foo
, the class attribute is modified in the init
method, that's why all instances are affected.
In foo2
, an instance variable is defined using the (empty) class attribute, and every instance gets its own bar
.
The "correct" implementation would be:
class foo:
def __init__(self, x):
self.bar = [x]
Of course, class attributes are completely legal. In fact, you can access and modify them without creating an instance of the class like this:
class foo:
bar = []
foo.bar = [x]