Python使用metaclass实现Singleton模式的方法

yipeiwu_com6年前Python基础

本文实例讲述了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获取文件路径、文件名、后缀名的实例

实例如下所示: #########start 获取文件路径、文件名、后缀名############ def jwkj_get_filePath_fileName_fileExt(fi...

恢复百度云盘本地误删的文件脚本(简单方法)

今天被同步盘搞得焦头烂额。 辛苦码的代码(除了重要的、备份过的)都被删掉了…… 当时我就石化了。。。 随后发现同步盘目录有个delete目录,里面还有manifest.xml,和一堆改了...

在python3中pyqt5和mayavi不兼容问题的解决方法

在python3中pyqt5和mayavi不兼容问题的解决方法

环境: win10 64bit & Linux Mint 18.2 WinPython3.6.1,spyder,qtconsole iep3.7 问题描述: 通过http://www.l...

python得到qq句柄,并显示在前台的方法

如下所示: # 导入模块 import win32gui win = win32gui.FindWindow(None, u'张三') # 将窗口调到前台 win32gui.Show...

python配置文件写入过程详解

python配置文件有.conf,.ini,.txt等多种 python集成的 标准库的 ConfigParser 模块提供一套 API 来读取和操作配置文件 我的配置文件如下 [M...