python 3.x 學習筆記5 (裝飾器),python3.x
1.裝飾器:
本質是函數,(裝飾其他函數)就是為其他函數添加附加功能
原則:
1)不能修改被裝飾的函數的原始碼
2)不能修改被裝飾的函數的調用方式
2.實現裝飾器知識儲備:
1)函數即“變數”
2)高階函數
a.把一個函數當作實參傳給另一個函數(可以做到不修改被裝飾函數的原始碼的情況下為其添加功能)
b.傳回值中包含函數名)(不修改函數的調用方式)
3)嵌套函數
3.高階函數+嵌套函數=》裝飾器
4.初步裝飾器
import timedef timer(func): #timer(test1) func = test1 def deco(): start_time = time.time() func() #run test1 stop_time = time.time() print('the func run time is %s'%(stop_time-start_time)) return deco@timer #test1 = timer(test1)def test1(): time.sleep(3) print('in the test1')test1()
5.功能比較完善的裝飾器
user,passwd = 'hsj','1234'def auth(auth_type): print('auth func:',auth_type) def outer_wrapper(func): def wrapper(*args, **kwargs): print('wrapper:',*args, **kwargs) if auth_type == 'local': username = input('Username:').strip() password = input('Password:').strip() if username == user and password == passwd: print('\033[32;1mUser has pass authentication\033[0m') return func(*args, **kwargs) # from home #函數wrapper的傳回值 else: exit('\033[31;1mInvalid username or password\033[0m') elif auth_type =='ldap': print('ldappppppppp') return wrapper return outer_wrapperdef index(): print('welcome to index psge')@auth(auth_type='local') # 加了括弧相當於運行了outer_wraper所以會執行裡面內容 # home = auth(home)def home(): print('welcome to home page') return 'from home' #這裡有傳回值在裝飾器裡也應該有個傳回值不然是print()不出來的@auth(auth_type='ldap')def bbs(): print('welcome to bbs page')index()print(home())bbs()