python單例模式原理與建立方法例項分析
阿新 • • 發佈:2020-01-09
本文例項講述了python單例模式原理與建立方法。分享給大家供大家參考,具體如下:
1. 單例是什麼
舉個常見的單例模式例子,我們日常使用的電腦上都有一個回收站,在整個作業系統中,回收站只能有一個例項,整個系統都使用這個唯一的例項,而且回收站自行提供自己的例項。因此回收站是單例模式的應用。
確保某一個類只有一個例項,而且自行例項化並向整個系統提供這個例項,這個類稱為單例類,單例模式是一種物件建立型模式。
2. 建立單例-保證只有1個物件
# 例項化一個單例 class Singleton(object): __instance = None def __new__(cls,age,name): #如果類數字__instance沒有或者沒有賦值 #那麼就建立一個物件,並且賦值為這個物件的引用,保證下次呼叫這個方法時 #能夠知道之前已經建立過物件了,這樣就保證了只有1個物件 if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance a = Singleton(18,"xxx") b = Singleton(8,"xxx") print(id(a)) print(id(b)) a.age = 19 #給a指向的物件新增一個屬性 print(b.age)#獲取b指向的物件的age屬性
執行結果:
4391023224
4391023224
19
3. 建立單例時,只執行1次init方法
# 例項化一個單例 class Singleton(object): __instance = None __first_init = False def __new__(cls,name): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance def __init__(self,name): if not self.__first_init: self.age = age self.name = name Singleton.__first_init = True a = Singleton(18,"xxx") print(id(a)) print(id(b)) print(a.age) print(b.age) a.age = 19 print(b.age)
執行結果:
139953926130600
139953926130600
18
18
19
更多關於Python相關內容可檢視本站專題:《Python資料結構與演算法教程》、《Python Socket程式設計技巧總結》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》及《Python入門與進階經典教程》
希望本文所述對大家Python程式設計有所幫助。