class
Singleton(type):
def __call__ (cls, * args):
if not hasattr(cls, ' instance ' ):
cls.instance = super(Singleton, cls). __call__ ( * args)
return cls.instance
class Cache(object):
__metaclass__ = Singleton
def main():
cache = Cache()
cache.data1 = 1
print ' data1 == %s ' % cache.data1
cache2 = Cache()
cache2.data1 = cache2.data1 + 1
print ' data1 is increased by 1. '
print ' data1 == %s ' % cache.data1
if __name__ == ' __main__ ' :
main()
def __call__ (cls, * args):
if not hasattr(cls, ' instance ' ):
cls.instance = super(Singleton, cls). __call__ ( * args)
return cls.instance
class Cache(object):
__metaclass__ = Singleton
def main():
cache = Cache()
cache.data1 = 1
print ' data1 == %s ' % cache.data1
cache2 = Cache()
cache2.data1 = cache2.data1 + 1
print ' data1 is increased by 1. '
print ' data1 == %s ' % cache.data1
if __name__ == ' __main__ ' :
main()
这是一个简单的meta programming的应用展示,展示了metaclass所蕴涵的强大的能力,只要想得到,metaclass可以实现各种各样用通常手法做不到或很难实现的功能。:D