我有一个类,它将所有创建的引用存储在静态列表中,如下所示:
class A: _List = [] def __init__(self): A._List.append(self) def __del__(self): A._List.remove(self)现在,如果我执行以下操作:
a = A() del aa不会被删除,因为它仍然在列表中引用。 但是如果将调用析构函数,则会破坏引用。 有没有办法以某种方式强制python执行__del__方法,以便它可以从静态列表中删除?
I have a class that stores all created references in a static list like this:
class A: _List = [] def __init__(self): A._List.append(self) def __del__(self): A._List.remove(self)Now if I do the following:
a = A() del aa 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?
最满意答案
你可以使用weakref.WeakValueDictionary (或weakref.WeakKeyDictionary ),它会自动删除任何不存在的元素:
class A(object): _instances = weakref.WeakValueDictionary() _next_id = functools.partial(next, itertools.count()) def __init__(self): self._instances[self._next_id()] = selfYou 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()] = selfPython:如何在引用所有已创建项目的类中实现静态列表以及删除项目的简单方法?(Python: How to implement a static list in a class referencing all created items and an easy way to delete the items?)我有一个类,它将所有创建的引用存储在静态列表中,如下所示:
class A: _List = [] def __init__(self): A._List.append(self) def __del__(self): A._List.remove(self)现在,如果我执行以下操作:
a = A() del aa不会被删除,因为它仍然在列表中引用。 但是如果将调用析构函数,则会破坏引用。 有没有办法以某种方式强制python执行__del__方法,以便它可以从静态列表中删除?
I have a class that stores all created references in a static list like this:
class A: _List = [] def __init__(self): A._List.append(self) def __del__(self): A._List.remove(self)Now if I do the following:
a = A() del aa 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?
最满意答案
你可以使用weakref.WeakValueDictionary (或weakref.WeakKeyDictionary ),它会自动删除任何不存在的元素:
class A(object): _instances = weakref.WeakValueDictionary() _next_id = functools.partial(next, itertools.count()) def __init__(self): self._instances[self._next_id()] = selfYou 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
发布评论