• 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]
  • 相关阅读:
    Java的学习笔记(二)
    Java的学习笔记
    简单界面生成
    登录界面
    播放器
    java计划
    求和
    修改后的抽奖系统
    第十周作业
    JAVA第五次作业
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11190046.html
Copyright © 2020-2023  润新知