python 单例
1
class Singleton: def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): cls._instance = object.__new__(cls) return cls._instance one = Singleton() two = Singleton() two.a = 3 print(one.a) # 3 # one和two完全相同,可以用id(), ==, is检测 print(id(one)) # 29097904 print(id(two)) # 29097904 print(one == two) # True print(one is two)
2 函数装饰器实现:实例化前先调用这个装饰器返回的 inner() 函数,再返回实例
def singleton2(cls): _instance = {} # 新建空字典; 不要_instance = None, 否则 inner 函数中赋值时,_instance 只会在函数作用域搜索,判断时会报错; def inner(): # 判断是否已有实例,如无,则新建一个实例并返回 if cls not in _instance: _instance[cls] = cls() return _instance[cls] # 返回的是实例对象 return inner @singleton2 class Cls(): def __init__(self): pass # 可以照常添加属性和方法 cls1 = Cls() cls2 = Cls() cls1 is cls2 # True