Python使用metaclass实现Singleton模式的方法
本文实例讲述了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程序设计有所帮助。
相关推荐
FlySky 2020-09-29
Phplayers 2020-09-05
oXiaoChong 2020-06-03
class Singleton: def __new__: # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象 if not hasattr: cls.instance =
lhxxhl 2020-05-16
laohyx 2020-04-06
pengkunstone 2020-02-22
codeAB 2020-01-19
逍遥友 2019-12-30
typhoonpython 2019-11-19
amazingbo 2019-06-30
pythonxuexi 2019-06-28
ruoyiqing 2016-10-13
cjb 2019-06-28
小方哥哥 2019-06-27
hualicc 2010-05-04
manbucy 2010-03-03
jibkfv 2019-06-20