相关疑难解决方法(0)

python中的weakref列表

我需要一个弱引用列表,它们会在项目死亡时删除它们.目前,我这样做的唯一方法是不断刷新列表(手动删除死引用).

我知道有一个WeakKeyDictionary和一个WeakValueDictionary,但我真的在WeakList之后,有没有办法做到这一点?

这是一个例子:

import weakref

class A(object):
    def __init__(self):
       pass

class B(object):
    def __init__(self):
        self._references = []

    def addReference(self, obj):
        self._references.append(weakref.ref(obj))

    def flush(self):
        toRemove = []

        for ref in self._references:
            if ref() is None:
                toRemove.append(ref)

        for item in toRemove:
            self._references.remove(item)

b = B()

a1 = A()
b.addReference(a1)
a2 = A()
b.addReference(a2)

del a1
b.flush()
del a2
b.flush()
Run Code Online (Sandbox Code Playgroud)

python weak-references

17
推荐指数
3
解决办法
7175
查看次数

标签 统计

python ×1

weak-references ×1