標籤:ima images order png ora open lock win 列印
關於裝飾器的更多資訊可以參考http://egon09.blog.51cto.com/9161406/1836763
1.裝飾器Decorator
裝飾器:本質上是函數,(裝飾其他函數),就是為其他函數添加附加功能
原則:不能修改被裝飾函數的原始碼;不能修改被裝飾函數的調用方式
#實現裝飾器的知識儲備:
1.函數即變數
2.高階函數,有兩種方式:
(1)把一個函數名當做實參傳遞給另一個函數(在不修改被裝飾函數原始碼的情況下為其添加功能)
(2)傳回值中包含函數名(不修改函數調用的方式)
3.嵌套函數
高階函數+嵌套函數==》裝飾器
import time#計算一個函數的已耗用時間的裝飾器def timer(func): def wrapper(*kargs,**kwargs): start_time=time.time() func() end_time=time.time() print("the func runtime is %s"%(end_time-start_time)) return wrapper@timerdef test1(): time.sleep(3) print("in the test1....")test1()
#高階函數def bar(): print("in the bar...")def test(func): print(func)#列印出該函數變數的地址 func()test(bar)
# 把一個函數名當做實參傳遞給另一個函數import timedef bar(): time.sleep(2) print("in the bar...")def test(func): start_time=time.time() func() #run bar() end_time=time.time() print(" the func runtime is %s"%(end_time-start_time))test(bar)
# 傳回值中包含函數名import timedef bar(): time.sleep(2) print("in the bar...")def test2(func): print(func) return funcbar2=test2(bar)bar2()
#嵌套函數#局部範圍和全域範圍的訪問順序x=0def grandpa(): x=1 print("grandpa:",x) def dad(): x=2 print("dad:",x) def son(): x=3 print("son:",x) son() dad()grandpa()
#匿名函數:沒有定義函數名字的函數calc=lambda x,y:x+yprint(calc(13,15))
import timedef timer(func): def deco(*kargs,**kwargs): start_time=time.time() func(*kargs,**kwargs) end_time=time.time() print(" the func runtime is %s"%(end_time-start_time)) return deco@timer # test1=timer(test1)def test1(): time.sleep(2) print("in the test1.....")# test1=timer(test1)test1()@timerdef test2(name,age): time.sleep(3) print("in the test2:",name,age)test2("Jean_V",20)
#裝飾器進階版#對各個頁面添加使用者認證username,password="admin","123"def auth(auth_type): print("auth_type:",auth_type) def out_wrapper(func): def wrapper(*args,**kwargs): if auth_type=="local": uname=input("請輸入使用者名稱:").strip() passwd=input("請輸入密碼:").strip() if uname==username and passwd==password: print("\033[32;1m User has passed authentication\033[0m") res=func(*args,**kwargs) print("************after authentication") print(res) else: exit("\033[31;1m Invalid username or password\033[0m") elif auth_type=="LADP": print("我不會LADP認證,咋辦?。。。") return wrapper return out_wrapperdef index(): print("index page......")@auth(auth_type="local")#home 頁採用本地驗證def home(): print("home page.....") return "from home page....."@auth(auth_type="LADP")#bbs 頁採用LADP驗證def bbs(): print("bbs page....")index()print(home())home()bbs()
第四周 day4 python學習筆記