单例模式__new__

单例模式,使用__new__

__new__是构造函数, __init__是初始化方法,先调用了__new__返回了实例,__init__给这个实例初始化绑定一些属性。

 1 class Singleton(object):
 2 
 3     def __new__(cls, *args, **kw):
 4         if not hasattr(cls, '_instance'):
 5             cls._instance = super(Singleton,cls).__new__(cls, *args, **kw)    
 6         
 7         return  cls._instance
 8    
 9     def __init__(self,name):
10         if not hasattr(self,'name'):      ##注意此行
11             self.name=name
12     
13     def __str__(self):
14         return '类的名称:%s 对象的name属性是:%s hash是:%s id是:%s '%(self.__class__.__name__,self.name, self.__hash__, id(self))
15     
16 x1=Singleton('xxxx')
17 x2=Singleton('yyyy')
18 
19 print id(x1)
20 print id(x2)
21 
22 print x1
23 print x2

观察结果可以发现,x1的name值是xxxx,x2的name的值也是xxxx。

如果去掉第10行,那么x1和x2的name的值都是yyyy。

在某些情况下需要控制某些属性不被重新赋值,就可以加入判断。特别是selenium webdriver的。

原文地址:https://www.cnblogs.com/ydf0509/p/8310833.html