zoukankan      html  css  js  c++  java
  • python 的单例

    例子

    class Singleton(object):
        _instance = None
        def __new__(cls, *args, **kw):
            if not cls._instance:
                cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)  
            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                                                        
    499807697384 499807697384                                   
    [Program finished]

    例子

    class test(object):
        _a=None
        def __init__(self):
            self.b=2
        def __new__(cls,*args,**kargs):
            if(not cls._a):
                cls._a=super(test,cls).__new__(cls,*args,**kargs)
            return cls._a
            
    
    x=test()
    print(x)
    print(x.b)
    y=test()
    print(y)
    print(y.b)

    输出

    <__main__.test object at 0x716e0fb9e8>
    2                                                           
    <__main__.test object at 0x716e0fb9e8>                      
    2                                                           
    [Program finished]
  • 相关阅读:
    CodeForces
    [AHOI 2013] 差异
    BZOJ
    [校内训练20_09_15]ABC
    [校内训练20_09_10]ABC
    [校内训练20_09_08]AC
    fastIO
    [校内训练20_06_05]ABC
    [校内训练20_06_04]ABC
    [校内训练20_06_03]ABC
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11190046.html
Copyright © 2011-2022 走看看