Python 單例模式

2022-09-03 08:09:12 字數 2160 閱讀 4880

相信大家學過程式語言對單例模式應該都很熟悉吧。今天就說一下在python 中單例模式的寫法。

1. 使用 __new__ 方式

1

class

mysingleton():

2def

__new__(cls, *args, **kwargs):3if

not hasattr(cls, '

_instance'):

4 cls._instance = super().__new__(cls, *args, **kwargs)

5return

cls._instance67

8 ms1 =mysingleton()

9 ms2 =mysingleton()

10print(id(ms1) == id(ms2))

>>> true

2. 裝飾器

1 def singleton_decorate(func):

2 intance_dict ={}34

def get_instance(*args, **kwargs):5#

if not intance_dict:6if

"instance

"not

inintance_dict:

7 intance_dict["

instance

"] =func()

8return intance_dict["

instance"]

910return

get_instance

1112

13@singleton_decorate

14class

singleton():

15pass

1617

18 s1 =singleton()

19 s2 =singleton()

20print(id(s1) == id(s2))

3. 元類

1

class

singleton(type):

2 instance ={}34

def__call__(cls, *args, **kwargs):5if

"instance

"not

incls.instance:

6 cls.instance["

instance

"] = super().__call__(*args, **kwargs)

7return cls.instance["

instance"]

8910class mycls(metaclass=singleton):

11pass

1213

14 mc1 =mycls()

15 mc2 =mycls()

16print(id(mc1) == id(mc2))

這是三種建立單例模式的方法。只是擴充套件一下。**之中用到了 __new__, __call__ 方法,其中還有 __init__ 方法,他們的作用是什麼?

__new__:

物件的建立會呼叫這個方法, 它是乙個靜態方法返回乙個類物件, 預設情況下是不需要寫的,可以 overide。

__init__:

說 __new__ 就必須說 __init__ 方法, 因為 __new__ 是建立物件,但是並沒有對物件進行初始化,而 __init__ 作用便是初始化物件, 載入物件資料, 也可以 overide。

__call__ :

我現階段了解的 __call__ 方法是, 類可以呼叫, 就是 a  = a() , a() 是生成物件,那 a() 這麼呢, 如果有 __call__ 方法的話, a() 就是呼叫 __call__ 方法。

上面**中 mycls 就是 

singleton 的物件,因為 

mycls 的元類是 

singleton

,在這裡解釋一下元類吧。

元類:我們都知道 類例項 是 類 的物件, 那麼 類 又是誰的物件呢?答案就是:元類, 元類的物件便是類,所以上面 元類這種單例模式就很好解釋了。

ps: 今天就和大家分享到這裡,如有不對,還請指正,謝謝。

共勉!

python單例模式繼承 python單例模式

我們可以使用 new 這個特殊方法。該方法可以建立乙個其所在類的子類的物件。更可喜的是,我們的內建 object 基類實現了 new 方法,所以我們只需讓 sing 類繼承 object 類,就可以利用 object 的 new 方法來建立 sing 物件了。classsing object def...

單例模式 python

單例模式 保證乙個類僅有乙個例項,並提供乙個訪問它的全域性訪問點。實現 某個類只有乙個例項 途徑 1 讓乙個全域性變數使得乙個物件被訪問,但是它不能防止外部例項化多個物件。2 讓類自身負責儲存它的唯一例項。這個類可以保證沒有其他例項可以被建立。即單例模式。多執行緒時的單例模式 加鎖 雙重鎖定。餓漢式...

python單例模式

new 在 init 之前被呼叫,用於生成例項物件。利用這個方法和類的屬性的特點可以實現設計模式的單例模式。單例模式是指建立唯一物件,單例模式設計的類只能例項 例項化1個物件。class singleton object instance none def init self pass def ne...