一、借助 __new__ 来实现
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
def __init__(self, x):
self.x = x
a = Singleton(1)
b = Singleton(2)
print a==b
print a.x, b.x
#True
#2 2
二、借助类属性与get函数
class Myclass(object):
_sigle_cls = None
def __init__(self, x):
self.x = x
@classmethod
def get_cls(cls, *args, **argk):
if not cls._sigle_cls:
cls._sigle_cls = cls(*args, **argk)
return cls._sigle_cls
a = Myclass.get_cls(1)
print a.x
b = Myclass.get_cls(2)
print "a.x:",a.x, "b.x", b.x
#a.x: 1 b.x 1
这两种方式还是有区别的,不知道看了此博文的同学发现了没?