python单例模式
1、使用__new__方法
class Single(object): _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance def __init__(self): pass
2、函数装饰器
def single(cls): _instance = {} def inner(*args, **kw): if cls not in _instance: _instance[cls] = cls(*args, **kw) return _instance[cls] return inner @single class Cls(object): pass
3、import
python的模块是天然的单例模式
# singleton.py class Single(object): def __init__(self, name): self.name = name single = Single('Alice') # use from singleton import single print(single.name)