Python新手學習裝飾器
python函數(shù)式編程之裝飾器
1.開放封閉原則
簡單來說,就是對擴展開放,對修改封閉。
在面向?qū)ο蟮木幊谭绞街?,?jīng)常會定義各種函數(shù)。一個函數(shù)的使用分為定義階段和使用階段,一個函數(shù)定義完成以后,可能會在很多位置被調(diào)用。這意味著如果函數(shù)的定義階段代碼被修改,受到影響的地方就會有很多,此時很容易因為一個小地方的修改而影響整套系統(tǒng)的崩潰,所以對于現(xiàn)代程序開發(fā)行業(yè)來說,一套系統(tǒng)一旦上線,系統(tǒng)的源代碼就一定不能夠再改動了。然而一套系統(tǒng)上線以后,隨著用戶數(shù)量的不斷增加,一定會為一套系統(tǒng)擴展添加新的功能。
此時,又不能修改原有系統(tǒng)的源代碼,又要為原有系統(tǒng)開發(fā)增加新功能,這就是程序開發(fā)行業(yè)的開放封閉原則,這時就要用到裝飾器了。
2.什么是裝飾器
裝飾器,顧名思義,就是裝飾,修飾別的對象的一種工具。
所以裝飾器可以是任意可調(diào)用的對象,被裝飾的對象也可以是任意可調(diào)用對象。
3.裝飾器的作用
在不修改被裝飾對象的源代碼以及調(diào)用方式的前提下為被裝飾對象添加新功能。
原則:
1.不修改被裝飾對象的源代碼
2.不修改被裝飾對象的調(diào)用方式
目標:
為被裝飾對象添加新功能。
實例擴展:
import time # 裝飾器函數(shù) def wrapper(func): def done(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print('the func run time is %s' % (stop_time - start_time)) return done # 被裝飾函數(shù)1 @wrapper def test1(): time.sleep(1) print("in the test1") # 被裝飾函數(shù)2 @wrapper def test2(name): #1.test2===>wrapper(test2) 2.test2(name)==dome(name) time.sleep(2) print("in the test2,the arg is %s"%name) # 調(diào)用 test1() test2("Hello World")
不含參數(shù)實例:
import time user,passwd = 'admin','admin' def auth(auth_type): print("auth func:",auth_type) def outer_wrapper(func): def wrapper(*args, **kwargs): print("wrapper func args:", *args, **kwargs) if auth_type == "local": username = input("Username:").strip() password = input("Password:").strip() if user == username and passwd == password: print("\033[32;1mUser has passed authentication\033[0m") res = func(*args, **kwargs) # from home print("---after authenticaion ") return res else: exit("\033[31;1mInvalid username or password\033[0m") elif auth_type == "ldap": print("ldap鏈接") return wrapper return outer_wrapper @auth(auth_type="local") # home = wrapper() def home(): print("welcome to home page") return "from home" @auth(auth_type="ldap") def bbs(): print("welcome to bbs page" print(home()) #wrapper() bbs()
到此這篇關于Python新手學習裝飾器的文章就介紹到這了,更多相關Python之裝飾器簡介內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python超越函數(shù)積分運算以及繪圖實現(xiàn)代碼
今天小編就為大家分享一篇Python超越函數(shù)積分運算以及繪圖實現(xiàn)代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11基于matplotlib中ion()和ioff()的使用詳解
這篇文章主要介紹了基于matplotlib中ion()和ioff()的使用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06如何基于Python代碼實現(xiàn)高精度免費OCR工具
這篇文章主要介紹了如何基于Python代碼實現(xiàn)高精度免費OCR工具,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06python matplotlib 注釋文本箭頭簡單代碼示例
這篇文章主要介紹了python matplotlib 注釋文本箭頭簡單代碼示例,具有一定借鑒價值。2018-01-01