本文实例讲述了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
singleton call
希望本文所述对大家的python程序设计有所帮助。