python 单例模式

#单例模式(不支持多线程)
import threading

class Single():
    f=None
    lock=threading.Lock()

    def __init__(self):
        pass

    def __new__(cls,*args,**kw):
        if Single.f==None:
            with Single.lock:  #加锁,防止多线程并发
                if Single.f==None:
                    Single.f=object.__init__(cls)
        return Single.f
    
s1=Single()
s2=Single()
print(id(s1))
print(id(s2))

 

class Single(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'_instance'):
            cls._instance=object.__new__(cls)
        return cls._instance
    def __init__(self,a,b):
        self.a=a
        self.b=b

class Single11(object):
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'_instance'):
            cls._instance=super().__init__(cls)
        return cls._instance

if __name__=='__main__':
    s=Single11(1,2)
    ss=Single11(1,2)
    print(id(s)==id(ss))

 

 2、父类继承初始化 __init__()

class Father():
    def __init__(self,a,b):
        self.a=a
        self.b=b

    def getA(self):
        return self.a

    def getB(self):
        return self.b

class Son(Father):
    def __init__(self,name,age,a,b):
        # Father.__init__(self,a,b)  #经典类的调用父类方式
        #super().__init__(a,b)       #新式类
        super(Son,self).__init__(a,b)#新式类

        self.name=name
        self.age=age

    def getInfo(self):
        print(self.name,self.age,self.a,self.b)

import threading
class Single():
    lock=threading.Lock()
    def __init__(self):
        pass
    def __new__(cls, *args, **kwargs):
        with Single.lock:                         #不确认这个方式是否可行,限制多线程
            if not hasattr(cls,"_instance"):
                cls._instance=object.__new__(cls)
        return cls._instance

class Singleton():
    def __init__(self,a,b):
        self.a=a
        self.b=b

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,"_instance"):
            #cls._instance=super().__new__(cls)  #三种方式调用父类的__new__
            #cls._instance=object.__new__(cls)
            cls._instance = super(Singleton,cls).__new__(cls)
        return cls._instance     
posted @ 2019-03-08 18:49  小金儿  阅读(140)  评论(0编辑  收藏  举报