我想要一个在对象引用计数更改时运行的方法。有没有类似下面代码的方法?
class Foo():
def __method__(self):
print("ojbect reference count is changed !")
a = Foo()
b = a # runs __method__ because the reference count is increased
c = b # runs __method__ because the reference count is increased
del b # runs __method__ because the reference count is decreased
del c # runs __method__ because the reference count is decreased
注意:这是this问题的转发,我正在寻找与Python 3.10兼容的答案。
谢谢!
我的对象的引用计数永远不会低于 1。以此为给定,我尝试通过添加
__del__
来实现一些清理代码,以便在所有面向用户的代码取消引用对象时实现一些清理代码。但这不起作用,因为还剩下一份参考资料。
所以,我需要添加一些清理代码以防止引用计数达到 1。
这是一个 XY 问题,我对此感到满意。我的实际情况涉及单例,其中
((User("my_name") == User("my_name")) and (User("my_name") != User("other_name"))) is True
。为此,有一个内部引用的字典来处理所有这些。这就是为什么对象的最小引用计数为 1。
当一个对象从用户代码中删除时,即引用计数达到1,我也想从我的引用字典中清除它。
我想要一个在对象引用计数更改时运行的方法。有没有类似下面代码的方法?
没有。
为此,有一个内部引用的字典可以处理所有这些。
使用弱引用?