Python装饰器
1.装饰器解释
1.1 装饰器它是一个函数,它包含了另一个函数的功能。它用于装饰被包含函数,为被包含的函数添加附加功能。
1.2 装饰器作用于被包含的函数,只有被包含的函数执行时,装饰器才起作用。
2.装饰器代码构成
2.1 函数嵌套(函数中包含另外函数,通俗讲:def 中还有 def )
2.2 高阶函数(返回函数)
3. 装饰器代码写法
3.1 二层装饰器代码
1 import time 2 3 4 def packing(func): 5 print('in the packing') 6 7 def deco(*args, **kwargs): 8 start_time = time.time() 9 func(*args, **kwargs) 10 stop_time = time.time() 11 print('the func run ', stop_time-start_time) 12 return deco 13 14 15 @packing # 等价于 test1 = packing(test1)(取得了deco的内存地址) 16 def test1(name): 17 time.sleep(1) 18 print('int the test1', name) 19 20 21 @packing 22 def test2(age, sex): 23 time.sleep(0.3) 24 print('in the test2', age, sex) 25 26 27 test1('alex') # 相当于执行deco() 28 test2(17, 'F')
3.2 三层装饰器代码
1 usrname = 'alex' 2 passwd = '123456' 3 def auth(auth_type): 4 def outpacking(func): 5 def packing(*args, **kwargs): 6 if auth_type == 'local': 7 name = input('input your usrname:\n') 8 pd = input('input your passowrd:\n') 9 if usrname == name and passwd == pd: 10 print('welcom %s' %usrname) 11 12 else: 13 print('\033[31;1minvalid usrname or password\033[0m') 14 exit() 15 elif auth_type == 'remote': 16 print('remote access your account') 17 func(*args, **kwargs) 18 return packing 19 return outpacking 20 21 def index(): 22 print('welcom to the index page') 23 24 25 @auth(auth_type='local') 26 def home(): 27 print('welcom to home page') 28 29 @auth(auth_type='remote') 30 def bbs(): 31 print('welcom to the bbs page') 32 33 34 index() 35 home() 36 bbs()