如何使 python class 对象依赖于另一个对象并在删除父对象时删除对象?

How to make python class objects dependent on another and delete the object when the parent is deleted?

我有两个 python classes A 和 B。 我希望 class A 依赖于 class B。 此外,当 class A 被删除时,class B 也应被删除。感谢您提供有关此事的任何帮助。

我试过用下面的代码实现这个。

class A:
    def __init__(self):
        self.newobj = B()
    def __del__(self):
        del self.newobj
        print('an object of class A was destroyed')

class B:
    def __init__(self):
         #do stuff
    def __del__(self):
        print('an object of class B was destroyed')

if __name__ == "__main__":

    
    obj1= A()
    obj2 = obj1.newobj

因为classA调用析构函数时,newobj没有被删除。 如果我尝试删除 class 析构函数中的 obj2,它会抛出一个错误,指出在赋值之前引用了 obj2。

用正常的引用,这是不可能的。当我们剩下零个引用时,资源的删除就完成了——你只是在 obj2 中做了一个你不能在不同范围内访问的引用(有人说 python 通过“赋值”传递参数——创建对对象的新引用)

但是,python 提供了弱引用。弱引用不计入垃圾收集。 https://docs.python.org/3/library/weakref.html

备注:

  • 垃圾收集器可能仍需要时间来收集父级(在下面的示例中我强制它收集)
  • 如果有人得到一个正常的引用,sub-object 将保持活力
import weakref 

class A:
    def __init__(self):
        self.__newobj = B()  # use double underscore in name to strongly suggest it shouldn't be used directly
    @property
    def newobj(self):
        return weakref.ref(self.__newobj)

class B:
    def __init__(self):
        self.test = "test"

obj1 = A()
weak_obj2 = obj1.newobj

我们通过调用引用来访问对象本身。不要将此调用存储在另一个变量中,因为那将是一个正常的引用。*

print(weak_obj2)  # <weakref at memoryaddresshere; to 'B' at anotheraddress>
print(weak_obj2())
print(weak_obj2().test)

让我们通过删除 obj1 并强制垃圾收集来测试它

del obj1
import gc
gc.collect()

print(weak_obj2)  # <weakref at memoryaddresshere; dead>
print(weak_obj2())  # None

正如我提到的,不要存储调用,因为它是一个正常的引用,并且会使 sub-object 保持活动状态。

obj1 = A()
weak_obj2 = obj1.newobj
obj2 = weak_obj2()  # storing the call

del obj1
gc.collect()
print(weak_obj2)  # not dead

del obj2
gc.collect()
print(weak_obj2)  # dead