zoukankan      html  css  js  c++  java
  • Python使用装饰器(decorator)实现单例模式

    #2.Python如何实现单例模式?其他23种设计模式python如何实现?
    #第一 使用__metaclass__(元类)的高级python用法
    #使用装饰器(decorator),
    #这是一种更pythonic,更elegant的方法,
    #单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的  # 使用装饰器(decorator),
    # 这是一种更pythonic,更elegant的方法,
    # 单例类本身根本不知道自己是单例的,因为他本身(自己的代码)并不是单例的
    
    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)
    print (id(one))
    print (id(two))
    print (one == two)
    print (two.x)
    one.x = 1
    print (one.x)
    print (one is two)
    # 3
    # 1541133085328
    # 1541133085328
    # True
    # 0
    # 1
    # True
     
  • 相关阅读:
    NGINX-HTTPS
    README
    SSH
    Ubuntu
    Python复利
    Python全双工聊天
    Python半双工聊天
    Python网络编程
    使用Python PIL库中的Image.thumbnail函数裁剪图片
    Python模块 os.walk
  • 原文地址:https://www.cnblogs.com/c-jw/p/13806750.html
Copyright © 2011-2022 走看看