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实现字符串反转的常用方法分析【4种方法】

本文实例讲述了Python实现字符串反转的常用方法。分享给大家供大家参考,具体如下: 下面是实现python字符串反转的四种方法: 1. 切片 def rev(s): return...

pandas 转换成行列表进行读取与Nan处理的方法

pandas中有时需要按行依次对.csv文件读取内容,那么如何进行呢? 我们来完整操作一遍,假设我们已经有了一个.csv文件。 # 1.导入包 import pandas as p...

python 3.5实现检测路由器流量并写入txt的方法实例

python 3.5实现检测路由器流量并写入txt的方法实例

前言 本文主要给大家介绍了关于利用python 3.5检测路由器流量并写入txt的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍。 环境交代:win10+pyth...

连接pandas以及数组转pandas的方法

pandas转数组 np.array(pandas) 数组转pandas pandas.DataFrame(numpy) pandas连接,只是左右接上,不合并值 df...

Python ORM框架SQLAlchemy学习笔记之数据查询实例

前期我们做了充足的准备工作,现在该是关键内容之一查询了,当然前面的文章中或多或少的穿插了些有关查询的东西,比如一个查询(Query)对象就是通过Session会话的query()方法获取...