Python下簡易的單例模式詳解

2022-09-29 06:03:07 字數 1932 閱讀 2803

python 下的單例模式

要點:方法:重寫new函式

應該考慮的情況:

要點:例項化的過程其實不是直接呼叫init的,首先是new分配一塊空間來建立例項,再由init對這個例項進行初始化.我們無法阻止new和init的呼叫,我們只能是限制他們的內容,以此使程式設計客棧他們能達到單例的目的

**:class people(object):

def __new__(cls,*args,**kargs):

return super(people程式設計客棧,cls).__new

def __init__(self,name):

self.name = name

def talk(self):

print("hello,i am %s" %self.name)

class student(people):

def __new__(cls,*args,**kargs):

if not hasattr(cls,"instance"):

cls.instance = super(student,cls).__new__(cls,*args,**kargs)

return cls.instance

a = student("timo")

print(a)

b = student("kysa")

c = student("luyi")

a.talk()

b.talk()

print(c)

這裡的輸出結果是:

<__main__.student object at>

hello,i am luyi

hello,i am luyi

<__main__.student object at>

可以確定的是: 確實是單例了,因為a的id和b,c的id是一致的

但是為什麼:a先建立明明是timowww.cppcns.com,可是為什麼a的name變成了luyi呢?

原因:雖然確實是a這個例項,但是在最後c重新呼叫了new,返回了a的例項,再經過init,改變了a的屬性,執行時name ->luyi.

解決:這種情況下,我們只需要設定類變數,讓init在類變數的限制下,只對類進行一次有效的初始化.

**:class people(object):

def __new__(cls,*args,**kargs):

return super(people,cls).__new__(cls)

def __init__(self,name):

s程式設計客棧elf.name = name

def talk(self):

print("hello,i am %s" %self.name)

class student(people):

def __new__(cls,*args,**kargs):

if not hasattr(cls,"instance"):

cls.instance = super(student,cls).__new__(cls,*args,**kargs)

return cls.instance

def __init__(self,name):

if not hasattr(self,"init_fir"):

self.init_fir = true

super(student,self).__init__(name)

a = student("timo")

print(a)

b = student("kysa")

c = student("luyi")

a.talk()

b.talk()

print(c)

好了,到這裡就用python實現了乙個簡易的單例模式.

本文標題: python下簡易的單例模式詳解

本文位址:

詳聊單例模式

發布物件 使乙個物件能夠被當前範圍之外的 所使用。物件逸出 一種錯誤的發布。當乙個物件還沒有構造完成時,就使它被其他執行緒所見。安全發布物件的4種方法 author title singletonex1 description 單例 懶漢模式 執行緒不安全 date 2020 4 11 15 16 ...

單例設計模式(注釋詳講)

1.什麼是設計模式 針對特定的問題提供的固定的最優的解決方案。在物件導向的程式語言中有23種設計模式 其中之一 單例設計模式 基本型別變數恒等比較比較的是兩個變數的值是否相等,引用型別變數恒等比較比較的是兩個引用變數引用的位址是否相等。1 餓漢式 注釋詳細解釋了為什麼這樣做 之所以叫餓漢式,是因為物...

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

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