使用元类的单例
单例是一种模式,它将类的实例化限制为一个实例/对象。有关 python singleton 设计模式的更多信息,请参见此处 。
class SingletonType(type):
def __call__(cls, *args, **kwargs):
try:
return cls.__instance
except AttributeError:
cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls.__instance
Python 2.x <= 2.7
class MySingleton(object):
__metaclass__ = SingletonType
Python 3.x >= 3.0
class MySingleton(metaclass=SingletonType):
pass
MySingleton() is MySingleton() # True, only one instantiation occurs