Python单例模式
单例模式:
装饰器形式:
```
import functools
def singleton(cls):
instance = None
@functools.wraps(cls)
def getinstance(*args,**kwargs):
nonlocal instance
if not instance:
print(args)
print(kwargs)
instance = cls(*args,**kwargs)
return instance
return getinstance
@singleton
class B:
def __init__(self,url,debug):
self.url = url
self.debug = debug
b = B(1,2)
print(id(b),b.__dict__,b.__doc__)
b1 = B(10,20)
print(id(b1),b1.__dict__,b1.__doc__)
```
```
new方法形式:
class A:
def __new__(cls, *args, **kwargs):
print('--------')
print(1,cls)
print(2,args)
print(3,kwargs)
if not hasattr(cls,'_instance'):
setattr(cls,'_instance',super().__new__(cls))
setattr(cls,'_count',0)
return cls._instance
def __init__(self,url,debug):
print('=======')
if self._count == 0 :
self.url = url
self.debug = debug
self.__class__.count = 1
else:
raise Exception('just one instance')
def __repr__(self):
return "<B{}{}>".format(self.url,self.debug)
b = A(1,debug=2)
print(4,b.__dict__)
print(id(b))
import time
time.sleep(2)
b1= A(2,debug=20)
print(5,b1.__dict__)
print(id(b1))
```