OOP - iterable class: how to delete one of its objects ?

Chris Angelico rosuav at gmail.com
Fri Nov 1 15:48:07 EDT 2019


On Sat, Nov 2, 2019 at 6:21 AM R.Wieser <address at not.available> wrote:
>
> Hello all,
>
> I've created a class from which I can iterate all its instanciated objects
> (using an "instances" list).    The problem is that I now cannot seem to
> delete an object anymore, AFAIK as a copy of its "self" is still inside the
> "instances" list.
>
> Object in question:
> - - - - - - - - - - - - - - - -
> class TheObject:
>     instances = []
>
>     def __init__(self):
>         self.instances.append(self)
>
>     def __del__(self):
>         print("Deleted!")
> - - - - - - - - - - - - - - - -
>
> The question: How can I keep the class iterable, but still have it delete
> itself when asked.
>

Have a method to explicitly purge the instance. The "del" statement
does NOT request that the object be deleted; it simply unbinds the
name. Instead, try something like this:

class TheObject:
    instances = []

    def __init__(self):
        self.active = True
        self.instances.append(self)

    def destroy(self):
        if not self.active: return
        self.active = False
        # wipe any attributes you need to
        self.instances.remove(self)

Then, instead of "del some_object", use "some_object.destroy()".

You can also use weak references if you need to, but this technique is
going to be a lot more reliable and dependable than something based on
weakrefs.

ChrisA


More information about the Python-list mailing list