单例:即一个类只能生成唯一的一个实例,python中的类如果没有被实例化,则cls._instance为None
如下:
class Singleton(object):
def __new__(cls,*args,**kw):
if not hasattr(cls,"_instance"):
orgi=super(Singleton,cls)
cls._instance=orgi.__new__(cls,*args,**kw)
return cls._instance
class MyClass(Singleton):
pass
one=MyClass()
two=MyClass()
print id(one)
print id(two)
print one==two
print one is two