Python: How to implement a static list in a class referencing all created items and an easy way to delete the items?
I have a class that stores all created references in a static list like this:
class A:
_Li开发者_运维技巧st = []
def __init__(self):
A._List.append(self)
def __del__(self):
A._List.remove(self)
Now if I do the following:
a = A()
del a
a
is not deleted, since it is still referenced to in the list. But the reference would be destroyed if the destructor would be called. Is there a way to somehow force python to execute the __del__
method anyway, so that it can get removed from the static list?
You can use weakref.WeakValueDictionary
(or weakref.WeakKeyDictionary
), it would automatcally remove any elements that do not exist anymore:
class A(object):
_instances = weakref.WeakValueDictionary()
_next_id = functools.partial(next, itertools.count())
def __init__(self):
self._instances[self._next_id()] = self
Use weakref.ref()
to create weak references to store in the list. Use a callback to remove entries from the list when the object no longer exists.
精彩评论