您好,登錄后才能下訂單哦!
一、理論知識(shí):
定義:裝飾器本身是函數(shù),就是為了為其他函數(shù)添加附加功能。
原則:
1、不能修改被修飾函數(shù)的源代碼
2、不能修改被修飾函數(shù)的調(diào)用方式
裝飾器知識(shí)必備:
1、函數(shù)即“變量”
2、高階函數(shù)
a:把一個(gè)函數(shù)名作為實(shí)參傳給另外一個(gè)函數(shù)
b:返回值中包含函數(shù)值
3、嵌套函數(shù)
高階函數(shù)+嵌套函數(shù)=》裝飾器
二、低潮版
import time def timmer(func): def bar(*args,**kwargs):#*args,**kwargs:表示非固定參數(shù) start_time=time.time() func(*args,**kwargs) stop_time=time.time() print ('the func run time %s'%(stop_time-start_time)) return bar#只是返回了內(nèi)存地址,并沒有運(yùn)行bar()函數(shù) @timmer#調(diào)用裝飾器timmer。相當(dāng)于:test1=timmer(test1) def test1():#由于返回bar()的地址,所以test1=timmer(test1)=bar time.sleep(3) print ('in the test1') @timmer def test2(name): print ('in the test2',name) #test1 = timmer(test1)#把返回的bar()函數(shù)內(nèi)存地址賦值給test1 test1() test2(2)
三、高潮版
當(dāng)被修飾函數(shù)中出現(xiàn)返回值(return 'from home')
user,passwd= 'peter','123qwe' def auth(auth_type): print ('auth_type:',auth_type) def outer(func): def warpper(*args,**kwargs): print ('warpper:',*args,**kwargs) username = input ('Username:').strip() password = input ('Password:').strip() if (user==username and passwd ==password): print ('\033[32;1mUser has passed authentication\033[0m') te=func(*args,**kwargs)#相當(dāng)于執(zhí)行home(*args,**kwargs) print ('----------') return te else: exit('\033[31;1mInvalid username or password\033[0m') return warpper return outer def index(): print ('welcome to index page') @auth(auth_type='local') def home(name): print ('welcome to home page',name ) return 'from home' @auth(auth_type='lodap') def bbs(): print ('welcome to bbs page') index() print (home(2)) bbs()
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。