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

2024-04-27 04:36:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类结构,其中一个类的实例需要保存对另一个类实例的引用。阅读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

我有一种感觉,第一种选择更可取,但我试图理解为什么。在我的例子中,引用的对象不可能在另一个对象之前被删除


Tags: 对象实例方法selfrefinitdefsome
1条回答
网友
1楼 · 发布于 2024-04-27 04:36:52

为了完整起见,我将写下这个答案,这是@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.

相关问题 更多 >