1. 利用__metaclass__
这种写法的好处是,一处声明,到处引用,只要是想弄成单例的,直接设置就可以了,废话不说上代码
# 注意,继承type
class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
class Test(object):
# __metaclass__
__metaclass__ = Singleton
t1 = Test()
t2 = Test()
print t1 == t2
想深入了解, 可以搜索python type详解,以及python类初始化的流程
2. 每个类单独写
这种写法好处是,可以给自己的单例类加上特有的逻辑
class MyTest(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
# 两种写法,实际上都是为了调用object.__new__
cls._instance = object.__new__(cls, *args, **kwargs)
# cls._instance = super(MyTest, cls).__new__(cls, *args, **kwargs)
return cls._instance
a = MyTest()
b = MyTest()
print a == b