在Python中销毁Singleton对象

时间:2017-04-25 19:51:19

标签: python python-3.x metaprogramming

我在Python中有一个Singleton对象:

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

    @classmethod
    def destroy(cls):
        del cls._instances[cls]


class MockObject(metaclass=Singleton):

    def __init__(self, *args, **kwargs):
        # various things

我想在某个时候销毁对象,所以我在元类中编写了一个类方法。但是,cls指的是元类Singleton而不是MockObject。有没有办法用值destroy来调用MockObject函数?

1 个答案:

答案 0 :(得分:11)

不是定义用于删除实例引用的自定义方法,而是使用WeakValueDictionary

现在,当MockObject的任何地方没有更多引用时,它会自动从Singleton._instances清除。

from weakref import WeakValueDictionary


class Singleton(type):
    _instances = WeakValueDictionary()

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            # This variable declaration is required to force a
            # strong reference on the instance.
            instance = super(Singleton, cls).__call__(*args, **kwargs)
            cls._instances[cls] = instance
        return cls._instances[cls]


class MockObject(metaclass=Singleton):

    def __init__(self, *args, **kwargs):
        pass


if __name__ == '__main__':
    m = MockObject()
    print(dict(Singleton._instances))
    del m
    print(dict(Singleton._instances))

<强>输出:

{<class '__main__.MockObject'>: <__main__.MockObject object at 0x104531128>}
{}