赶紧入手,python面试题之Python如何实现单例模式?
生活随笔
收集整理的這篇文章主要介紹了
赶紧入手,python面试题之Python如何实现单例模式?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
你現在在找工作嗎?還是在觀望中呢?快過年了,很多人都會想先存點錢,把年過好再說吧。為了春節,我們加油!哈哈。
回到找工作的話題,遇到心儀的公司了,不可否定的是:最后還是得過了面試那一關。所以,面試前把準備做足了,這樣才能增加面試成功的幾率。
?
廢話不多說,python面試題之Python如何實現單例模式,直接給大家送上干貨:
#使用__metaclass__(元類)的高級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的方法, #單例類本身根本不知道自己是單例的,因為他本身(自己的代碼)并不是單例的 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開發工程師,這里有我自己整理了一套最新的python系統學習教程,包括從基礎的python腳本到web開發、爬蟲、數據分析、數據可視化、機器學習等。想要這些資料的可以關注小編,并在點擊:“資料? 即可領取。
總結
以上是生活随笔為你收集整理的赶紧入手,python面试题之Python如何实现单例模式?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ubuntu 编译安装opencv官网教
- 下一篇: 【Python】【小明爬楼梯】