Reputation: 13
I am trying to make a GUI and I need to be able to delete the instantiated object that is within the Comic class (in the comics list). I also need to be able to delete it from the list of names. (comic_names)
This is my function for finding the object to delete
def delete_comic():
for c in comics:
if c._name == delete_selected_comic.get():
c._delete_comic()
update_label()
This is my class, function and function for actually deleting the object.
class Comic:
def __init__(self, name, stock):
self._name = name
self._stock = stock
comics.append(self)
comic_names.append(name)
def _delete_comic(self):
self._stock = 0
self._name = ""
del self
Setting stock and name to 0 and blank doesn't actually remove the object and i am not sure how to use del self.
Any help on how to delete this object would be greatly appricated. Thanks in advance
Upvotes: 0
Views: 112
Reputation: 1951
del self
does almost nothing -- it only deletes the local variable named self. But as that isn't the last reference to the instance (it still exists in your list and possibly the calling method) so the object will continue to exist.
To effectively delete the object, delete its reference in the list, and anywhere else it may be stored.
del comics[desired_index]
Upvotes: 0
Reputation: 1643
You cannot delete an object within itself. Instead, you can set it to None
and let the garbage collector delete it:
def delete_comic():
for i, c in enumerate(comics):
if c._name == delete_selected_comic.get():
comics[i] = None
update_label()
If you really want to delete the object right there, you can do this:
def delete_comic():
delete_indicies = []
for i, c in enumerate(comics):
if c._name == delete_selected_comic.get():
delete_indicies.append(i)
for i in delete_indicies:
del comics[i]
update_label()
Upvotes: 1