国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 枣庄市| 高淳县| 武胜县| 二连浩特市| 新干县| 潮州市| 石狮市| 壤塘县| 滦南县| 崇仁县| 监利县| 江山市| 泰兴市| 新乡县| 元江| 外汇| 崇仁县| 天柱县| 兴安县| 巴楚县| 余干县| 万安县| 南充市| 武威市| 阳曲县| 包头市| 鞍山市| 天长市| 宣化县| 苍山县| 和林格尔县| 成都市| 灌阳县| 陈巴尔虎旗| 龙口市| 谢通门县| 林甸县| 分宜县| 柏乡县| 泉州市| 林西县|