• 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     
  • 相关阅读:
    LLVM 3.0 — LinuxTOY
    Fabric Engine 1.0
    tmux:GNU screen 替代品 — LinuxTOY
    LuoYun 开源云计算平台软件 0.2 Beta 版本发布 — LinuxTOY
    迅雷离线下载脚本 — LinuxTOY
    Vim 状态栏是 Powerline 插件。
    LuoYun 云计算平台 0.4 版本 liveCD 发布
    webOS Isis 开源 — LinuxTOY
    Impress.js — LinuxTOY
    从 screen 切换到 tmux — LinuxTOY
  • 原文地址:https://www.cnblogs.com/xiaoxiao075/p/10497640.html
Copyright © 2020-2023  润新知