Python使用metaclass实现Singleton模式的方法,metaclasssingleton
Python使用metaclass实现Singleton模式的方法,metaclasssingleton
本文实例讲述了Python使用metaclass实现Singleton模式的方法。分享给大家供大家参考。具体实现方法如下:
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中变量的拷贝和作用域问题,python变量
- Python闭包实现计数器的方法,python闭实现计数器
- python中的闭包用法实例详解,python用法实例详解
- 简单介绍Python中的try和finally和with方法,pythonfinally
- 用Python实现一个简单的多线程TCP服务器的教程,python
- 给Python中的MySQLdb模块添加超时功能的教程,pythonmysql
- python实现的简单窗口倒计时界面实例,python实例
- python基于Tkinter库实现简单文本编辑器实例,
- python实现将汉字转换成汉语拼音的库,python汉语拼音
- python去除所有html标签的方法,python去除标签
评论关闭