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程序设计有所帮助。

相关文章

python3 破解 geetest(极验)的滑块验证码功能

下面一段代码给大家介绍python破解geetest 验证码功能,具体代码如下所示: from selenium import webdriver from selenium.web...

python实现机器学习之元线性回归

python实现机器学习之元线性回归

一、理论知识准备 1.确定假设函数 如:y=2x+7 其中,(x,y)是一组数据,设共有m个 2.误差cost 用平方误差代价函数 3.减小误差(用梯度下降)...

Python numpy实现数组合并实例(vstack,hstack)

若干个数组可以沿不同的轴合合并到一起,vstack,hstack的简单用法, >>> a = np.floor(10*np.random.random((2,2))...

pymongo中聚合查询的使用方法

pymongo中聚合查询的使用方法

前言 在使用mongo数据库时,简单的查询基本上可以满足大多数的业务场景,但是试想一下,如果要统计某一荐在指定的数据中出现了多少次该怎么查询呢?笨的方法是使用find 将数据查询出来,再...

Python使用getpass库读取密码的示例

Python使用getpass库读取密码的示例

有这样一个经历,服务器挂掉了,请工程师维护,为了安全,工程师进行核心操作时,直接关掉显示器进行操作,完成后,再打开显示器,进行收尾工作... 密码 这个经历告诉我们: 为了安全...