博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python单例模式
阅读量:5824 次
发布时间:2019-06-18

本文共 1804 字,大约阅读时间需要 6 分钟。

#-*- 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._instanceclass MyClass(Singleton):    a = 1one = MyClass()two = MyClass()two.a = 3print one.a#3#one和two完全相同,可以用id(), ==, is检测print id(one)print id(two)print one == two#Trueprint one is two#Trueclass Borg(object):    _state = {}    def __new__(cls, *args, **kw):        ob = super(Borg, cls).__new__(cls, *args, **kw)        ob.__dict__ = cls._state        return obclass MyClass2(Borg):    a = 1one = MyClass2()two = MyClass2()two.a = 3print one.aprint id(one)print id(two)print one == twoprint one is twoclass 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._instanceclass MyClass3(object):    __metaclass__ = Singleton2one = MyClass3()two = MyClass3()two.a = 3print one.a#3print id(one)#31495472print id(two)#31495472print one == two#Trueprint one is two#Truedef singleton(cls, *args, **kw):    instances = {}    def _singleton():        if cls not in instances:            instances[cls] = cls(*args, **kw)        return instances[cls]    return _singleton@singletonclass MyClass4(object):    a = 1    def __init__(self, x=0):        self.x = xone = MyClass4()two = MyClass4()two.a = 3print one.a#3print id(one)#29660784print id(two)#29660784print one == two#Trueprint one is two#Trueone.x = 1print one.x#1print two.x#1

class3使用了元类。 

class4使用了美妙的decorator。

转载于:https://www.cnblogs.com/tom-zhao/p/4135604.html

你可能感兴趣的文章
java中回调函数以及关于包装类的Demo
查看>>
maven异常:missing artifact jdk.tools:jar:1.6
查看>>
终端安全求生指南(五)-——日志管理
查看>>
Nginx 使用 openssl 的自签名证书
查看>>
创业维艰、守成不易
查看>>
PHP环境安装套件:快速安装LAMP环境
查看>>
CSS3
查看>>
ul下的li浮动,如何是ul有li的高度
查看>>
C++ primer plus
查看>>
python mysqlDB
查看>>
UVALive 3942 Remember the Word Tire+DP
查看>>
Android之HttpClient
查看>>
从微软的DBML文件中我们能学到什么(它告诉了我们什么是微软的重中之重)~目录...
查看>>
被需求搞的一塌糊涂,怎么办?
查看>>
c_数据结构_队的实现
查看>>
jquery 选择器总结
查看>>
1月10日,11日工作情况
查看>>
Qt设置背景图片
查看>>
Grunt使用心得
查看>>
【阿里云文档】常用文档整理
查看>>