初識python: 裝飾器
阿新 • • 發佈:2018-10-05
實現 輸入 其它 dex ron 地址 驗證方式 .... star
定義:
本質是函數,功能是“裝飾”其它函數,即為其他函數添加附加功能
原則:
1、不能修改被裝飾函數的源代碼;
2、不能修改被裝飾函數的調用方式
實現裝飾器知識儲備:
1、函數即“變量”;
2、高階函數;
3、嵌套函數。
實例1:初始版
# 定義裝飾器函數 import time def qt_fun(func): def gj_func(*args,**kwargs): #關鍵點,定義不定實參傳入值個數*args,形參個數**kwargs start_time=time.time() func(*args,**kwargs) #關鍵點,傳入參數 stop_time=time.time() print(‘運行時間:‘,stop_time-start_time) return gj_func #關鍵點,返回值。 @qt_fun #關鍵點,引用裝飾器,相當於:test1 = qt_fun(test1) def test1(name): time.sleep(1) print(‘姓名:‘,name) @qt_fun #關鍵點,引用裝飾器,test2 = qt_fun(test2) test2() def test2(name,age,addrs): time.sleep(2) print(‘姓名:%s 年齡:%s 地址:%s‘%(name,age,addrs)) #test1 = qt_fun(test1) #test1() #可替換成 @qt_fun @裝飾器名 #調用函數 test1(‘simple‘) test2(‘simple‘,26,‘四川‘)
實例2:終極版
user_name = ‘simple‘ password = ‘123‘ def choose_type(c_type): def login_f(func): def in_fun(*args,**kwargs): ifc_type == ‘A‘: print(‘當前選擇的驗證方式為:‘, c_type) name=input(‘用戶名:‘).strip() passwd=input(‘密碼:‘).strip() if name==user_name and passwd==password: print(‘登錄成功!‘) func(*args,**kwargs) else: exit(‘用戶名或密碼不正確,登錄失敗!‘) elif c_type == ‘B‘: print(‘當前選擇的驗證方式為:‘, c_type) print(‘此驗證方式,開發中....‘) else: print(‘輸入的驗證方式不正確!‘) return in_fun return login_f @choose_type(c_type=input(‘請選擇home的驗證方式(A/B):‘).strip()) def home(): print(‘歡迎進入主頁!‘) @choose_type(c_type=input(‘請選擇bbs的驗證方式(A/B):‘).strip()) def bbs(): print(‘歡迎進入bbs界面!‘) def index(): print(‘歡迎光臨index界面!此界面無需驗證!‘) home() bbs() index()
輸出結果:
初識python: 裝飾器