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如何去除字符串中不想要的字符

问题:     过滤用户输入中前后多余的空白字符       ‘    ++++abc123---    ‘     过滤某w...

python机器人运动范围问题的解答

机器人的运动范围Python实现: 问题:地上有个 m 行 n 列的方格。一个机器人从坐标(0,0)的格子开始移动,它每一次可以向左、右、上、下移动一格,但不能进入行坐标和列坐标的数位之...

Python 操作MySQL详解及实例

Python 操作MySQL详解及实例 使用Python进行MySQL的库主要有三个,Python-MySQL(更熟悉的名字可能是MySQLdb),PyMySQL和SQLAlchemy。...

Python autoescape标签用法解析

Python autoescape标签用法解析

这篇文章主要介绍了Python autoescape标签用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.spaceless...

《Python学习手册》学习总结

《Python学习手册》学习总结

本篇文章是作者关于在学习了《Python学习手册》以后,分享的学习心得,在此之前,我们先给大家分享一下这本书: 下载地址:Python学习手册第4版 之前为了编写一个svm分词的程序而...