tags:

views:

45

answers:

1

I have a Python class containing a list, to which I append() values.

If I delete an object of this class then create a second object later on in the same script, the second object's list is the same as the first's was at the time of deletion.

For example:

class myObj:
    a = []
    b = False

o = myObj()
o.a.append("I'm still here!")
o.b = True

del o
import gc
gc.collect() # just to be safe
o = myObj()

print(o.a) # ["I'm still here!"]
print(o.b) # False

There is a way to empty the list:

while len(o.a):
    o.a.pop()

But that's ridiculous, not to mention slow. Why is it still in memory after garbage collection, and more to the point why is it not overwritten when the class inits? All non-list member vars are handled correctly. append(), extend() and insert() all lead to the same result -- is there another method I should be using?

Here's my full test script. Notice how Python gives an AttributeError if I try to delete a member list directly, even though I can read from it fine.

+9  A: 

When you create a variable inside a class declaration, it's a class attribute, not an instance attribute. To create instance attributes you have to do self.a inside a method, e.g. __init__.

Change it to:

class myObj:
    def __init__(self):
        self.a = []
        self.b = False
Skilldrick
that was it, thanks
Artfunkel