zoukankan      html  css  js  c++  java
  • Python单例模式

    单例模式:

    装饰器形式:

    ```
    import functools

    def singleton(cls):

    instance = None

    @functools.wraps(cls)

    def getinstance(*args,**kwargs):

    nonlocal instance

    if not instance:

    print(args)

    print(kwargs)

    instance = cls(*args,**kwargs)

    return instance

    return getinstance

    @singleton

    class B:

    def __init__(self,url,debug):

    self.url = url

    self.debug = debug

    b = B(1,2)

    print(id(b),b.__dict__,b.__doc__)

    b1 = B(10,20)

    print(id(b1),b1.__dict__,b1.__doc__)
    ```

    ```
    new方法形式:
    class A:

    def __new__(cls, *args, **kwargs):

    print('--------')

    print(1,cls)

    print(2,args)

    print(3,kwargs)

    if not hasattr(cls,'_instance'):

    setattr(cls,'_instance',super().__new__(cls))

    setattr(cls,'_count',0)

    return cls._instance

    def __init__(self,url,debug):

    print('=======')

    if self._count == 0 :

    self.url = url

    self.debug = debug

    self.__class__.count = 1

    else:

    raise Exception('just one instance')

    def __repr__(self):

    return "<B{}{}>".format(self.url,self.debug)

    b = A(1,debug=2)

    print(4,b.__dict__)

    print(id(b))

    import time

    time.sleep(2)

    b1= A(2,debug=20)

    print(5,b1.__dict__)

    print(id(b1))
    ```

  • 相关阅读:
    event的属性
    dom三个事件
    setInterval和setTimeout定时器
    eclipse编码格式设置
    eclipse Subversion Native Library Not Available
    NET Framework V4.0.30319
    eclipse配置tomcat
    eclipse Multiple annotations found at this line
    eclipse安装svn插件
    eclipse安装maven
  • 原文地址:https://www.cnblogs.com/wangchunli-blogs/p/9951278.html
Copyright © 2011-2022 走看看