用 __new__函数实现单例模式,主要思想,当创建第二个对象的时候,返回第一个对象
1 #!/usr/bin/python 2 #coding=utf-8 3 4 class Singleton(object): 5 def __new__(cls,*args,**kw): 6 if not hasattr(cls,'_instance'): 7 orig=super(Singleton,cls) 8 cls._instance=orig.__new__(cls,*args,**kw) 9 return cls._instance 10 11 class MyClass(Singleton): 12 a=1 13 14 one=MyClass() 15 two=MyClass() 16 17 print id(one) 18 print id(two) 19 20 one.a=3 21 print one.a 22 print two.a