国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-23 01:04:08
字體:
來源:轉載
供稿:網(wǎng)友

本文實例講述了Python使用metaclass實現(xiàn)Singleton模式的方法。分享給大家供大家參考。具體實現(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 newSingleton initSingleton callCache newCache init<__main__.Cache object at 0x01CDB130>Singleton call<__main__.Cache object at 0x01CDB130>

希望本文所述對大家的Python程序設計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 佳木斯市| 曲周县| 平远县| 庆安县| 沈丘县| 曲周县| 桑植县| 麦盖提县| 金门县| 慈利县| 郎溪县| 惠东县| 武山县| 汝阳县| 绍兴县| 尤溪县| 泰顺县| 阿巴嘎旗| 海淀区| 垫江县| 时尚| 万源市| 涞源县| 许昌市| 中卫市| 贡觉县| 平顶山市| 延边| 库伦旗| 平原县| 谷城县| 元谋县| 思茅市| 湄潭县| 哈巴河县| 石泉县| 旺苍县| 安徽省| 岫岩| 长治市| 苍山县|