python单例模式你搞懂了么?我是终于懂了~
创建Singleton.py文件
class A(object):
def foo(self):
print('test')
v = A()
===============================================
创建另一文件,调用该实例
from singleton import A as a1
from singleton import A as a2
print(a1, id(a1))
print(a2, id(a2))
二、通过__new__方法
主要思路:在一个类的new方法中判断是不是存在实例,如果存在就直接返回,不存在就创建。
class singleton(object):
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
# 是否有实例,没用则创建一个实例
if not hasattr(cls, '_instance'):
singleton._instance = object.__new__(cls)
return singleton._instance
obj1 = singleton()
obj2 = singleton()
print(obj1, obj2)
三、装饰器
def Singleton(cls, *args, **kargs):
_instance = {} # 创建空字典
def get_instance(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls] # 返回实例
return get_instance # 返回内层函数
class Settings():
def __init__(self):
self.a = 'abc'
s1 = Settings()
s2 = Settings()
print(s1, s2)
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock() # 加锁
def __init__(self):
time.sleep(1)
def instance(cls, *args, **kwargs):
with Singleton._instance_lock: # 加锁
if not hasattr(Singleton, '_instance'):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
def test(arg):
obj1 = Singleton.instance()
obj2 = Singleton.instance()
print(obj1, obj2)
1
历史推荐
来都来了,点个在看再走吧~~~