Python单例模式 Aug 24, 2018 • Silver 继承模式-无锁 class Singleton(object): _instance = None def __new__(cls,*args,**kwargs): if not cls._instance: cls._instance=super(Singleton,cls).__new__( cls,*args,**kwargs ) return cls._instance 继承模式-双检锁 import threading class Singleton(object): objs={} objs_locker = threading.Lock() def __new__(cls,*args,**kv): if cls in cls.objs: return cls.objs[cls] with objs_locker: if cls in cls.objs: return cls.objs[cls] cls.objs[cls]=object.__new__(cls) 元类(metaclass)模式-无锁 class Singleton(type): def __init__(cls,name,bases,dic): super(Singleton,cls).__init__(name,bases,dic) cls.instance = None def __call__(cls,*args,**kwargs): if cls.instance is None: print "creating a new instance" cls.instance=super(Singleton,cls).__call__(*args,**kwargs) else: print "warning: only allowed to create one instance, instance already exists!" return cls.instance class MySingleton(object): __metaclass__ = Singleton import模式-无需加锁 # singleton.py class Singleton(object): def __init__(self): pass def do_sth(self): pass single = Singleton() # main.py import singleton print singleton.single.do_sth() Reference: 继承模式 元类模式