Python使用metaclass实现Singleton模式的方法
2015-05-05 00:00
796 查看
本文实例讲述了Python使用metaclass实现Singleton模式的方法。分享给大家供大家参考。具体实现方法如下:
输出:
希望本文所述对大家的Python程序设计有所帮助。
class Singleton(type): def __call__(cls, *args, **kwargs): print "Singleton call" if not hasattr(cls, 'instance'): cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instance def __new__(cls, name, bases, dct): print "Singleton new" return type.__new__(cls, name, bases, dct) def __init__(cls, name, bases, dct): print "Singleton init" super(Singleton, cls).__init__(name, bases, dct) class Cache(object): __metaclass__ = Singleton def __new__(cls, *args, **kwargs): print "Cache new" return object.__new__(cls, *args, **kwargs) def __init__(cls, *args, **kwargs): print "Cache init" def __call__(cls, *args, **kwargs): print "Cache call" print Cache() print Cache()
输出:
Singleton new Singleton init Singleton call Cache new Cache init <__main__.Cache object at 0x01CDB130> Singleton call <__main__.Cache object at 0x01CDB130>
希望本文所述对大家的Python程序设计有所帮助。
相关文章推荐
- Python使用metaclass实现Singleton模式的方法
- Python中使用 metaclass 实现Singleton 模式
- Python实现__metaclass__实现方法运行时间统计
- Python 使用list实现堆栈 (基于class, 包含迭代器)
- Python 使用单链表实现堆栈 (基于class, 包含迭代器)
- Python 使用list实现队列 (基于class, 包含迭代器)
- Python 使用循环数组实现队列 (基于class, 包含迭代器)
- Python 使用单链表实现队列 (基于class, 包含迭代器)
- Python 使用list实现无边际优先队列 (基于class, 包含迭代器)
- Python 使用由单链表构建的数组实现有边际优先队列 (基于class, 包含迭代器)
- 结合rpyc使用python实现动态升级的方法
- python使用cStringIO实现临时内存文件访问的方法
- 使用Python的元类实现AOP监控类方法调用过程
- 在 Python 中实现 Ruby 的 Open Class 和特异方法
- python使用multiprocessing模块实现带回调函数的异步调用方法
- python使用fileinput模块实现逐行读取文件的方法
- 使用ShellClass获取文件属性详细信息的实现方法
- 一种分析代金券使用分布情况的方法python实现版(上)
- 一种分析代金券使用分布情况的方法python实现版(下)
- python基础教程之类class定义使用方法