Can someone explain why Python does the following?
>>> class Foo(object):
... bar = []
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar.append(1)
>>> b.bar
[1]
>>> a.bar = 1
>>> a.bar
1
>>> b.bar
[1]
>>> a.bar = []
>>> a.bar
[]
>>> b.bar
[1]
>>> del a.bar
>>> a.bar
[1]
It’s rather confusing!
As others have said the code as written creates a class variable rather than an instance variable. You need to assign in
__init__to create an instance variable.Hopefully this annotated copy of your code is helpful in explaining what’s going on at each stage:
Also, printing out the value of
Foo.bar(the class variable accessed via the class rather than via an instance) after each of your statements might help clarify what is going on.