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设计模式大全

本文实例讲述了python常见的设计模式。分享给大家供大家参考,具体如下: # #!/usr/bin/env python # # -*- coding:utf-8 # # clas...

举例介绍Python中的25个隐藏特性

注:这里忽略了生成器,装饰器,交换变量等熟知技巧 1. 函数参数unpack 老生常谈的了:   def foo(x, y): print x, y alist...

Python使用pyh生成HTML文档的方法示例

Python使用pyh生成HTML文档的方法示例

最近在项目中需要将结果导出到HTML中,在网上搜索的时候发现了这个库,通过官方的一些文档以及网上的博客发现它的使用还是很简单的,因此选择在项目中使用它。 在使用的时候发现在Python3...

Python面向对象程序设计之继承与多继承用法分析

本文实例讲述了Python面向对象程序设计之继承与多继承。分享给大家供大家参考,具体如下: 1. 继承 在C++和Java中,使用继承时,子类的构造函数会自动调用父类的构造函数,但在Py...

python控制台实现tab补全和清屏的例子

在shell(bash)下有2个很基本的功能,那就是tab补全,和clear清屏,对于我这种时不时不自觉的就手残要clear清屏一下的人来说,python控制台不能清屏很不爽,经过goo...