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

首頁 > 編程 > Python > 正文

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

2019-11-25 17:32:53
字體:
供稿:網(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ā)表
主站蜘蛛池模板: 安化县| 油尖旺区| 黄浦区| 云阳县| 克拉玛依市| 郯城县| 屏边| 阜宁县| 高唐县| 嘉义市| 临邑县| 霍林郭勒市| 广安市| 景德镇市| 文水县| 景洪市| 上犹县| 吕梁市| 剑阁县| 兰州市| 饶阳县| 邵武市| 封开县| 浑源县| 安徽省| 来宾市| 营口市| 囊谦县| 镇巴县| 桐柏县| 南通市| 塘沽区| 隆子县| 栾川县| 顺平县| 元朗区| 阜平县| 新郑市| 泰宁县| 长治县| 贺州市|