风火编程--python单例模式, 支持主动更新

python3, 支持更新的单例模式

直接上代码

# coding: utf-8

from threading import Lock
class A():
    _instance_lock = Lock()
    __instance = None
    __has_initialization = False
    def __new__(cls, *args, **kwargs):
        with cls._instance_lock:
            if not cls.__instance:
                cls.__instance = object.__new__(cls)
        return cls.__instance

    def __init__(self, name):
        if not A.__has_initialization:
            self.name = name
           A.__has_initialization = True

    @classmethod
    def rebuild(cls):
        cls.__instance = None
        cls.__has_initialization = False

if __name__ == '__main__':
    a = A("风火")
    b = A("windfire")
    print(a.name)
    print(b.name)
    A.rebuild()
    c = A("77245741")
    print(c.name)

你可能感兴趣的:(python基础)