[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))對象

相關文章
相關標籤/搜索