标签:dig button state article super __call__ let import tin
利用“装饰器只会执行一次”这个特点
1 def singleton(cls): 2 instances = []# 为什么这里不直接为None,因为内部函数没法访问外部函数的非容器变量 3 def getinstance(*args, **kwargs): 4 if not instances: 5 instances.append(cls(*args, **kwargs)) 6 return instances[0] 7 return getinstance 8 9 @singleton 10 class Foo: 11 a = 1 12 13 f1 = Foo() 14 f2 = Foo() 15 print id(f1), id(f2)
利用“类变量对所有对象唯一”,即cls._instance
1 class Singleton(object): 2 def __new__(cls, *args, **kwargs): 3 if not hasattr(cls, ‘_instance‘): 4 cls._instance = object.__new__(cls, *args, **kwargs) 5 return cls._instance 6 7 class Foo(Singleton): 8 a = 1
利用“类变量对所有对象唯一”,即cls._instance
1 class Singleton(type): 2 def __call__(cls, *args, **kwargs): 3 if not hasattr(cls, ‘_instance‘): 4 cls._instance = super(Singleton, cls).__call__(*args, **kwargs) 5 return cls._instance 6 7 class Foo(): 8 __metaclass__ = Singleton
利用“类变量对所有对象唯一”,即__share_state
1 class Foo: 2 __share_state = {} 3 def __init__(self): 4 self.__dict__ = self.__share_state
利用“模块只会被import一次”
1 #在文件mysingleton中 2 class Foo(object): 3 pass 4 5 f = Foo()
然后在其它模块,from mysingleton import f
直接拿f当作单例的对象来用
标签:dig button state article super __call__ let import tin
原文地址:http://www.cnblogs.com/lpxblog/p/7267960.html