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

    #-*- encoding=utf-8 -*-
    class Singleton(object):
        def __new__(cls, *args, **kw):
            if not hasattr(cls, '_instance'):
                orig = super(Singleton, cls)
                cls._instance = orig.__new__(cls, *args, **kw)
            return cls._instance
    
    class MyClass(Singleton):
        a = 1
    
    one = MyClass()
    two = MyClass()
    
    two.a = 3
    print one.a
    #3
    #one和two完全相同,可以用id(), ==, is检测
    print id(one)
    
    print id(two)
    
    print one == two
    #True
    print one is two
    #True
    
    class Borg(object):
        _state = {}
        def __new__(cls, *args, **kw):
            ob = super(Borg, cls).__new__(cls, *args, **kw)
            ob.__dict__ = cls._state
            return ob
    
    class MyClass2(Borg):
        a = 1
    
    one = MyClass2()
    two = MyClass2()
    
    two.a = 3
    print one.a
    print id(one)
    print id(two)
    print one == two
    print one is two
    
    class Singleton2(type):
        def __init__(cls, name, bases, dict):
            super(Singleton2, cls).__init__(name, bases, dict)
            cls._instance = None
        def __call__(cls, *args, **kw):
            if cls._instance is None:
                cls._instance = super(Singleton2, cls).__call__(*args, **kw)
            return cls._instance
    
    class MyClass3(object):
        __metaclass__ = Singleton2
    
    one = MyClass3()
    two = MyClass3()
    
    two.a = 3
    print one.a
    #3
    print id(one)
    #31495472
    print id(two)
    #31495472
    print one == two
    #True
    print one is two
    #True
    
    
    def singleton(cls, *args, **kw):
        instances = {}
        def _singleton():
            if cls not in instances:
                instances[cls] = cls(*args, **kw)
            return instances[cls]
        return _singleton
    
    @singleton
    class MyClass4(object):
        a = 1
        def __init__(self, x=0):
            self.x = x
    
    one = MyClass4()
    two = MyClass4()
    
    two.a = 3
    print one.a
    #3
    print id(one)
    #29660784
    print id(two)
    #29660784
    print one == two
    #True
    print one is two
    #True
    one.x = 1
    print one.x
    #1
    print two.x
    #1

    class3使用了元类。 

    class4使用了美妙的decorator。

  • 相关阅读:
    go语言学习之从例子开始
    分享一个不错的Unittest测试报告
    selenium各种定位方法(转)
    HTMLTESTRunner自动化测试报告增加截图功能
    selenium之chrome驱动版本
    Python基础(六) python生成xml测试报告
    vue+elementUI 表头按钮
    vue+elementUI滚动条
    vue表格表头添加按钮
    elementUI升级版本后Dialog弹空不显示问题
  • 原文地址:https://www.cnblogs.com/tom-zhao/p/4135604.html
Copyright © 2011-2022 走看看