标签:线程 div IV sel style self href tor one
def singleton(class_): instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance @singleton class MyClass(BaseClass): pass
class Singleton(object): _instance = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance class MyClass(Singleton, BaseClass): pass
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] #Python2 class MyClass(BaseClass): __metaclass__ = Singleton #Python3 class MyClass(BaseClass, metaclass=Singleton): pass
def singleton(class_): class class_w(class_): _instance = None def __new__(class_, *args, **kwargs): if class_w._instance is None: class_w._instance = super(class_w, class_).__new__(class_, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w @singleton class MyClass(BaseClass): pass
支持多线程:
import time import threading def singleton(class_): class class_w(class_): _instance_lock = threading.Lock() _instance = None def __new__(class_, *args, **kwargs): if class_w._instance is None: # time.sleep(2) with class_w._instance_lock: if class_w._instance is None: class_w._instance = super(class_w, class_).__new__(class_, *args, **kwargs) class_w._instance._sealed = False return class_w._instance def __init__(self, *args, **kwargs): if self._sealed: return super(class_w, self).__init__(*args, **kwargs) self._sealed = True class_w.__name__ = class_.__name__ return class_w class BaseClass(object): pass @singleton class MyClass(BaseClass): pass if __name__ == ‘__main__‘: def task(arg): obj = MyClass() print(id(obj)) for i in range(10): t = threading.Thread(target=task, args=[i, ]) t.start() time.sleep(20) obj = MyClass() print(id(obj)) # for i in range(100): # my_obj = MyClass() # print(id(my_obj))
标签:线程 div IV sel style self href tor one
原文地址:https://www.cnblogs.com/liuwei0824/p/9234873.html