[Tips] python实现单例

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

利用python装饰器能够单例对象,@的语法糖的意义在于.net

My = singleton(My(*args, **kw))对象

相关文章
相关标签/搜索