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

yipeiwu_com5年前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关于调用函数外的变量实例

实例如下所示: class Solution(object): def foo(self, s): def bar(a): s += a prin...

基于pandas将类别属性转化为数值属性的方法

基于pandas将类别属性转化为数值属性的方法

离散特征的编码分为两种情况: 1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码 2、离散特征的取值有大小的意义,比如size:[...

Python实现PyPDF2处理PDF文件的方法示例

Python实现PyPDF2处理PDF文件的方法示例

实际应用中,可能会涉及处理 pdf 文件,PyPDF2 就是这样一个库,使用它可以轻松的处理 pdf 文件,它提供了读,割,合并,文件转换等多种操作。 文档地址:http://pytho...

Python下的subprocess模块的入门指引

Python下的subprocess模块的入门指引

在熟悉了Qt的QProcess以后,再回头来看python的subprocess总算不觉得像以前那么恐怖了。 和QProcess一样,subprocess的目标是启动一个新的进程并与之进...

python刷投票的脚本实现代码

原理就是用代理IP去访问投票地址。用到了多线程,速度飞快。 昨晚两个小时就刷了1000多票了,主要是代理IP不好找。 2.7环境下运行 #!/usr/bin/env python...