0

I want to delete or overwrite a python object.

First, here is simple class.

>>> def Myclass():
...    def __init__(self, name, value=[]):
...        self.name = name
...        self.value = value
...

Then I create an object of Myclass and add something to the value attribute.

>>> m1 = Myclass('m1')
>>> m1.value.append('a')
>>> m1.value.append('b')
>>> m1.value
['a', 'b']

Now I try to delete it.

>>> del m1
>>> m1.value  ### the variable seem to be properly erased
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'm1' is not defined

Seems to be properly deleted. I try to create a new object with the same name (because I want to overwrite the old values).

>>> m1 = Myclass('m1')
>>> m1.value
['a', 'b'] ### The previous value was not erased!!

It seems the del command on python is not actually deleting the variable. Do I need to manually call the garbage collector to erase it?

I'm using python 3.6.3

mparada
  • 158
  • 8
  • 1
    Your problem is nothing to do with `del`. This: `def __init__(self, name, value=[])` is called a "mutable default argument", and it is nearly always not what you want. – khelwood Dec 07 '17 at 09:41
  • You are deleting...and then trying to access? – user1767754 Dec 07 '17 at 09:41

0 Answers0