Python新手學(xué)習(xí)裝飾器
python函數(shù)式編程之裝飾器
1.開放封閉原則
簡(jiǎn)單來說,就是對(duì)擴(kuò)展開放,對(duì)修改封閉。
在面向?qū)ο蟮木幊谭绞街校?jīng)常會(huì)定義各種函數(shù)。一個(gè)函數(shù)的使用分為定義階段和使用階段,一個(gè)函數(shù)定義完成以后,可能會(huì)在很多位置被調(diào)用。這意味著如果函數(shù)的定義階段代碼被修改,受到影響的地方就會(huì)有很多,此時(shí)很容易因?yàn)橐粋€(gè)小地方的修改而影響整套系統(tǒng)的崩潰,所以對(duì)于現(xiàn)代程序開發(fā)行業(yè)來說,一套系統(tǒng)一旦上線,系統(tǒng)的源代碼就一定不能夠再改動(dòng)了。然而一套系統(tǒng)上線以后,隨著用戶數(shù)量的不斷增加,一定會(huì)為一套系統(tǒng)擴(kuò)展添加新的功能。
此時(shí),又不能修改原有系統(tǒng)的源代碼,又要為原有系統(tǒng)開發(fā)增加新功能,這就是程序開發(fā)行業(yè)的開放封閉原則,這時(shí)就要用到裝飾器了。
2.什么是裝飾器
裝飾器,顧名思義,就是裝飾,修飾別的對(duì)象的一種工具。
所以裝飾器可以是任意可調(diào)用的對(duì)象,被裝飾的對(duì)象也可以是任意可調(diào)用對(duì)象。
3.裝飾器的作用
在不修改被裝飾對(duì)象的源代碼以及調(diào)用方式的前提下為被裝飾對(duì)象添加新功能。
原則:
1.不修改被裝飾對(duì)象的源代碼
2.不修改被裝飾對(duì)象的調(diào)用方式
目標(biāo):
為被裝飾對(duì)象添加新功能。
實(shí)例擴(kuò)展:
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ù)實(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新手學(xué)習(xí)裝飾器的文章就介紹到這了,更多相關(guān)Python之裝飾器簡(jiǎn)介內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
