单例模式

用__new__实现单例模式

class Singleton(object):
    _instance=None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance=super(Singleton,cls).__new__(cls,*args,**kwargs)
        #cls._instance=super().__new__(cls,*args,**kwargs)#python3可以直接简写成super().xxx
    return cls._instance

class Myclass(Singleton):
    a=1

one=Myclass()
two=Myclass()
print(one==two)
print(one is two)
print(id(one),id(two))

#True
#True
#1268707849048 1268707849048

 参考

http://funhacks.net/2017/01/17/singleton/

posted @ 2018-12-05 00:24  Operater  阅读(154)  评论(0编辑  收藏  举报