python 單例

方法1:使用裝飾器(decorator)

def singleton(cls, *args, **kw):    
    instances = {}    
    def _singleton():    
        if cls not in instances:    
            instances[cls] = cls(*args, **kw)    
        return instances[cls]    
    return _singleton    
  
@singleton    
class MyClass(object):    
    a = 1    
    def __init__(self, x=0):    
        self.x = x    
    
one = MyClass()    
two = MyClass()    
    
two.a = 3    
print one.a    
#3    
print id(one)    
#29660784    
print id(two)    
#29660784    
print one == two    
#True    
print one is two    
#True    
one.x = 1    
print one.x    
#1    
print two.x  
3
35607384
35607384
True
True
1
1

方法2:使用metaclass元類來實現(xiàn)

class Singleton2(type):    
    def __init__(cls, name, bases, dict):    
        super(Singleton2, cls).__init__(name, bases, dict)    
        cls._instance = None    
    def __call__(cls, *args, **kw):    
        if cls._instance is None:    
            cls._instance = super(Singleton2, cls).__call__(*args, **kw)    
        return cls._instance    
    
class MyClass(object):    
    __metaclass__ = Singleton2    
    
one = MyClass()    
two = MyClass()    
    
two.a = 3    
print one.a    
#3    
print id(one)    
#31495472    
print id(two)    
#31495472    
print one == two    
#True    
print one is two    
3
47911488
47911488
True
True

方法3:通過共享屬性來實現(xiàn),所謂共享屬性,最簡單直觀的方法就是通過dict屬性指向同一個字典dict

class Borg(object):    
    _state = {}    
    def __new__(cls, *args, **kw):    
        ob = super(Borg, cls).__new__(cls, *args, **kw)    
        ob.__dict__ = cls._state    
        return ob    
    
class MyClass(Borg):    
    a = 1    
    
one = MyClass()    
two = MyClass()    
    
#one和two是兩個不同的對象,id, ==, is對比結(jié)果可看出    
two.a = 3    
print one.a    
#3    
print id(one)    
#28873680    
print id(two)    
#28873712    
print one == two    
#False    
print one is two    
#False    
#但是one和two具有相同的(同一個__dict__屬性),見:    
print id(one.__dict__)    
#30104000    
print id(two.__dict__)    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 單例模式 單例模式(Singleton Pattern)是一種常用的軟件設(shè)計模式,該模式的主要目的是確保某一個類只...
    小爆蝦丶閱讀 220評論 0 0
  • 本系列文章是希望將軟件項目中最常見的設(shè)計模式用通俗易懂的語言來講解清楚,并通過Python來實現(xiàn),每個設(shè)計模式都是...
    geekpy閱讀 19,860評論 6 36
  • Python單例模式 單例模式 單例模式是一種常用的軟件設(shè)計模式。在它的核心結(jié)構(gòu)中只包含一個被稱為單例類的特殊類。...
    smile念殤閱讀 501評論 0 4
  • 重寫new方法 裝飾器版本 import導(dǎo)入
    FangHao閱讀 498評論 0 1
  • 今天開始新篇章:成長的煩惱。記錄孩子們好玩的不好玩的煩惱。 今早,我爬起來做了老家一個小吃:炸糖糕。把面粉用開水燙...
    日出東方天剛曉閱讀 313評論 1 0

友情鏈接更多精彩內(nèi)容