def singleton(cls): ins= {} def _tmp(): if cls not in ins: ins[cls] = cls(*args, **kw) return ins[cls] return _tmp @singleton class My(object): a = 1 def __init__(self, x=0): self.x = x # one和two是同一个对象 one = My() two = My()
(代码参考自https://blog.csdn.net/ghostfromheaven/article/details/7671853,感谢博主)
利用python装饰器可以单例对象,@的语法糖的意义在于
My = singleton(My(*args, **kw))