装饰器单例
def singleton(cls): instances = []# 为什么这里不直接为None,因为内部函数没法访问外部函数的非容器变量 def getinstance(*args, **kwargs): if not instances: instances.append(cls(*args, **kwargs)) return instances[0] return getinstance @singleton class Foo: a = 1 f1 = Foo() f2 = Foo() print id(f1), id(f2)
重写__new__
利用“类变量对所有对象唯一”,即cls._instance
class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, '_instance'): cls._instance = object.__new__(cls, *args, **kwargs) return cls._instance class Foo(Singleton): pass