一、理論知識:
定義:裝飾器本身是函數,就是為了為其他函數添加附加功能。
原則:
1、不能修改被修飾函數的源代碼
2、不能修改被修飾函數的調用方式
裝飾器知識必備:
1、函數即“變量”
2、高階函數
a:把一個函數名作為實參傳給另外一個函數
b:返回值中包含函數值
3、嵌套函數
高階函數+嵌套函數=》裝飾器
二、低潮版
import time def timmer(func): def bar(*args,**kwargs):#*args,**kwargs:表示非固定參數 start_time=time.time() func(*args,**kwargs) stop_time=time.time() print ('the func run time %s'%(stop_time-start_time)) return bar#只是返回了內存地址,并沒有運行bar()函數 @timmer#調用裝飾器timmer。相當于: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()函數內存地址賦值給test1 test1() test2(2)
三、高潮版
當被修飾函數中出現返回值(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)#相當于執行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()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。