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]
  • 相关阅读:
    Redis其他命令
    Redis 键(key)
    Redis数据类型命令
    配置命令 CONFIG
    Redis简介
    idea破解
    jenkins+allure+testng
    Jenkins
    docker镜像
    docker命令
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11190046.html
Copyright © 2011-2022 走看看