使用元類的單例

單例是一種模式,它將類的例項化限制為一個例項/物件。有關 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