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 Kmeans算法原理深入解析

python Kmeans算法原理深入解析

一. 概述 首先需要先介绍一下无监督学习,所谓无监督学习,就是训练样本中的标记信息是位置的,目标是通过对无标记训练样本的学习来揭示数据的内在性质以及规律。通俗得说,就是根据数据的一些内...

PyQt5实现拖放功能

PyQt5实现拖放功能

在这节教程中,我们将探讨PyQt5中的拖放操作。 在计算机图形用户界面(GUI)中,拖放是在某个虚拟对象上点击并拖动到另一个位置或虚拟对象上的操作。它通常用于调用多个动作,或为两个抽象对...

在vscode中配置python环境过程解析

在vscode中配置python环境过程解析

1.安装vscode和python3.7(安装路径在:E:\Python\Python37); 2.打开vscode,在左下角点击设置图标选择setting,搜索python path,...

Python selenium 父子、兄弟、相邻节点定位方式详解

今天跟大家分享下selenium中根据父子、兄弟、相邻节点定位的方法,很多人在实际应用中会遇到想定位的节点无法直接定位,需要通过附近节点来相对定位的问题,但从父节点定位子节点容易,从子节...

Python列表推导式的使用方法

1.列表推导式书写形式:   [表达式 for 变量 in 列表]    或者  [表达式 for 变量 in 列表 if 条件] 2.举例说明:...