赶紧入手,python面试题之Python如何实现单例模式?
生活随笔
收集整理的這篇文章主要介紹了
赶紧入手,python面试题之Python如何实现单例模式?
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?
你現(xiàn)在在找工作嗎?還是在觀望中呢?快過年了,很多人都會(huì)想先存點(diǎn)錢,把年過好再說吧。為了春節(jié),我們加油!哈哈。
回到找工作的話題,遇到心儀的公司了,不可否定的是:最后還是得過了面試那一關(guān)。所以,面試前把準(zhǔn)備做足了,這樣才能增加面試成功的幾率。
?
廢話不多說,python面試題之Python如何實(shí)現(xiàn)單例模式,直接給大家送上干貨:
#使用__metaclass__(元類)的高級(jí)python用法 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 MyClass3(object): __metaclass__ = Singleton2 one = MyClass3() two = MyClass3() two.a = 3 print one.a #3 print id(one) #31495472 print id(two) #31495472 print one == two #True print one is two#True#使用裝飾器(decorator), #這是一種更pythonic,更elegant的方法, #單例類本身根本不知道自己是單例的,因?yàn)樗旧?自己的代碼)并不是單例的 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 MyClass4(object): a = 1 def __init__(self, x=0): self.x = x one = MyClass4() two = MyClass4() 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 #1趕緊收藏起來吧~
最后多說一句,小編是一名python開發(fā)工程師,這里有我自己整理了一套最新的python系統(tǒng)學(xué)習(xí)教程,包括從基礎(chǔ)的python腳本到web開發(fā)、爬蟲、數(shù)據(jù)分析、數(shù)據(jù)可視化、機(jī)器學(xué)習(xí)等。想要這些資料的可以關(guān)注小編,并在點(diǎn)擊:“資料? 即可領(lǐng)取。
總結(jié)
以上是生活随笔為你收集整理的赶紧入手,python面试题之Python如何实现单例模式?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu 编译安装opencv官网教
- 下一篇: websocket python爬虫_p