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@wrapperdef test1(): time.sleep(1) print('in the test1')# 被裝飾函數(shù)2@wrapperdef 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 timeuser,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 authentication033[0m') res = func(*args, **kwargs) # from home print('---after authenticaion ') return res else: exit('033[31;1mInvalid username or password033[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()
到此這篇關(guān)于Python新手學習裝飾器的文章就介紹到這了,更多相關(guān)Python之裝飾器簡介內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 詳解Android studio 動態(tài)fragment的用法2. 解決Android studio xml界面無法預覽問題3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. Spring Boot和Thymeleaf整合結(jié)合JPA實現(xiàn)分頁效果(實例代碼)5. php模擬實現(xiàn)斗地主發(fā)牌6. 什么是python的自省7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應用實現(xiàn)8. vue 使用localstorage實現(xiàn)面包屑的操作9. .Net Core使用Coravel實現(xiàn)任務調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備