每次访问 Weakref 对象时都应该调用它吗?

Should a Weakref object be called every time it's accessed?

我有一个 class 结构,其中一个 class 的实例需要保存对另一个实例的引用。通读 some other posts,最好(最安全)的方法是使用 weakref。它看起来像这样:

class ClassA:
    def __init__(self):
        self.my_b = ClassB(self)
        self.some_prop = 1

class ClassB:
    def __init__(self, some_a):
        self.some_a = weakref.ref(some_a)

我的问题是,要通过 ClassB 的实例访问 some_prop,您必须调用使对象可用的引用,as per documentation:

self.some_a().some_prop

但是,我的问题是是否应该每次都调用引用。我们不能只在 init 中调用 weakref 吗?即

self.some_a = weakref.ref(some_a)()

然后像

一样(更自然地)访问它
self.some_a.some_prop

我感觉第一个选项更可取,但我想了解原因。在我的例子中,引用的对象不可能先于另一个被删除。

为了完整起见,我将写下这个答案,它是@sanyash 评论的副本。

Python garbage collector is clever enough to detect cyclic references and delete both objects that reference each other if there is no reference to them in the outer scope. You really don't need to use weakref.