如何删除另一个模块创建的对象?

How to delete object created by another module?

以下是我的代码:

from ab import Ab

class Xyz:
    def __init__():
        self.a = Ab.get_unique_instance()

这就是 get_unique_instance() 函数在 ab.py

中的定义方式
 class Ab:
     instance = []
     def get_unique_instance():
         if len(Ab.instance) == 0:
             new_instance = Ab() 
             Ab.instance.append(new_instance)
         return Ab.instance[0]

这样做是为了确保只有一个 Ab 实例存在。问题是即使从 class Xyz 创建的对象超出范围,Ab 的实例仍在内存中。如何显式删除这个对象?

这是一种可能的实现方式,使用 weakref 确保只有 外部 引用(即 not Single._instance) 计入引用计数:

import weakref

class Single(object):

    _instance = None

    def __init__(self):
        print "I've been born"

    def __del__(self):
        print "I'm dying"

    @classmethod
    def get_instance(cls):
        if cls._instance is not None and cls._instance() is not None:
            return cls._instance()
        instance = cls()
        cls._instance = weakref.ref(instance)
        return instance

因此您一次最多有一个 Single,但如果删除所有引用,则可以有 none(并且将在下一次调用 [=24 时创建一个新的=] 方法)。使用中:

>>> a = Single.get_instance()
I've been born
>>> b = Single.get_instance()
>>> a is b
True
>>> del a
>>> del b
I'm dying
>>> c = Single.get_instance()
I've been born
>>> del c
I'm dying