最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用metaclass實(shí)現(xiàn)Singleton模式的方法

 更新時(shí)間:2015年05月05日 10:41:52   作者:鴣斑兔  
這篇文章主要介紹了Python使用metaclass實(shí)現(xiàn)Singleton模式的方法,實(shí)例分析了Python基于metaclass實(shí)現(xiàn)單例模式的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了Python使用metaclass實(shí)現(xiàn)Singleton模式的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

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>

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

都安| 民勤县| 岑溪市| 盐源县| 海城市| 正安县| 诸暨市| 宝山区| 福建省| 保康县| 马关县| 景宁| 独山县| 松江区| 兴文县| 鄯善县| 分宜县| 攀枝花市| 安达市| 绥中县| 大同县| 曲阳县| 库尔勒市| 大新县| 宁陵县| 东乌| 临颍县| 微山县| 宣恩县| 迁西县| 梅州市| 大庆市| 藁城市| 葵青区| 丰原市| 松潘县| 江口县| 巴彦县| 莎车县| 崇州市| 双辽市|