python - 跟踪对对象实例的引用

标签 python

这或多或少是我跟踪类实例数量的方式,因为每次创建一个实例时都会调用 __new__ :

class MyClass():
    def __new__(klass):
        try:
            klass.__instances = klass.__instances + 1
        except NameError:
            klass.__instances = 1
        return super(MyClass,klass).__new__(klass)

当对类的特定实例进行新引用时,是否有一个神奇的方法被调用?如果没有,是否有一种直接的方法来实现?例如:

class MyClass():
    def __init__(self):
        self.__ref = 1
        print(self,"created.")
    def __new_reference(self):
        self.__ref = self.__ref + 1
        print("Reference to",self,"added.")
    def __del_reference(self):
        self.__ref = self.__ref - 1
        print("Reference to",self,"deleted.")

现在:

L1 = []
L2 = []
L1.append(MyClass()) #<MyClass object> created
L1[0].__ref          #1
L2.append(L1[0])     #Reference to <MyClass object> added.
L2[0].__ref          #2
L1.pop(0)            #Reference to <MyClass object> deleted.
L2[0].__ref          #1

编辑:

Here's the problem我想我会尝试使用引用跟踪来解决。

我的想法是拥有一个对象A实例,其中包含对对象B的多个(弱)引用。有一个单独的列表,其中包含所有有效的 B。还有所有 A 的列表(数千个)。理想的行为是,当从 B 列表中删除任何一个 B 时,任何对象 A 都将变为 None 如果它包含对从 B 列表中删除的特定 B 的引用。

最佳答案

据我所知,没有什么神奇的方法可以做到这一点,但也许你可以使用 sys.getrefcount() :

Return the reference count of the object. The count returned is generally one higher than you might expect, because it includes the (temporary) reference as an argument to getrefcount().

使用您的示例:

>>> import sys
>>> class MyClass: pass
... 
>>> L1 = []
>>> L2 = []
>>> L1.append(MyClass())
>>> sys.getrefcount(L1[0])
2
>>> L2.append(L1[0])
>>> sys.getrefcount(L1[0])
3
>>> del L1[0]
>>> sys.getrefcount(L2[0])
2

关于python - 跟踪对对象实例的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27053928/

相关文章:

python - 测试 python 备忘录装饰器

python - django-filer 上传自动创建模型的实例

python - 在 cx_oracle 中返回一个存储过程输出游标变量

python - 如何在 python 中同时运行多个循环函数?

Python furl 库 - 有没有办法在没有 url 编码的情况下将参数添加到 url?

python - 如何对 Tornado 进行单元测试?

python - 如何获取方法参数名称?

python - Pandas:将 csv 文件加载为列表

python - 使用字典进行数据帧聚合

python - 使用 Xampp 运行 Python 脚本