日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 四种单例模式

發(fā)布時間:2025/5/22 python 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 四种单例模式 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1 2 1 使用__new__方法 3 Python 4 class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instanceclass MyClass(Singleton): a = 1 5 6 7 8 9 10 class Singleton(object): 11 def __new__(cls, *args, **kw): 12 if not hasattr(cls, '_instance'): 13 orig = super(Singleton, cls) 14 cls._instance = orig.__new__(cls, *args, **kw) 15 return cls._instance 16 17 class MyClass(Singleton): 18 a = 1 19 2 共享屬性 20 創(chuàng)建實例時把所有實例的__dict__指向同一個字典,這樣它們具有相同的屬性和方法. 21 22 Python 23 class Borg(object): _state = {} def __new__(cls, *args, **kw): ob = super(Borg, cls).__new__(cls, *args, **kw) ob.__dict__ = cls._state return obclass MyClass2(Borg): a = 1 24 25 26 27 28 29 30 class Borg(object): 31 _state = {} 32 def __new__(cls, *args, **kw): 33 ob = super(Borg, cls).__new__(cls, *args, **kw) 34 ob.__dict__ = cls._state 35 return ob 36 37 class MyClass2(Borg): 38 a = 1 39 3 裝飾器版本 40 Python 41 def singleton(cls, *args, **kw): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls(*args, **kw) return instances[cls] return getinstance@singletonclass MyClass: ... 42 43 44 45 46 47 48 def singleton(cls, *args, **kw): 49 instances = {} 50 def getinstance(): 51 if cls not in instances: 52 instances[cls] = cls(*args, **kw) 53 return instances[cls] 54 return getinstance 55 56 @singleton 57 class MyClass: 58 ... 59 4 import方法 60 作為python的模塊是天然的單例模式 61 62 Python 63 # mysingleton.pyclass My_Singleton(object): def foo(self): passmy_singleton = My_Singleton()# to usefrom mysingleton import my_singletonmy_singleton.foo() 64 65 66 67 # mysingleton.py 68 class My_Singleton(object): 69 def foo(self): 70 pass 71 72 my_singleton = My_Singleton() 73 74 # to use 75 from mysingleton import my_singleton 76 77 my_singleton.foo()

?

轉(zhuǎn)載于:https://www.cnblogs.com/chengyunshen/p/7196280.html

總結(jié)

以上是生活随笔為你收集整理的python 四种单例模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。