〖Python〗-- 装饰器补充

【装饰器补充】

装饰器前奏:

装饰器变形:

(1)第一种变形

(2)第二种变形

(3)第三种变形

(4)第四种变形(正确且标准得装饰器)

装饰器装饰带有参数的函数:

 

带标志位的装饰器:

 

应用场景:例如装饰器是为了测试代码运行时间,但是生产环境上线是需要去掉多余得功能,这时候可以把装饰器标志位改为False即可,避免了频繁的删除操作。

带参数的装饰器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import time
 
current_login = {'name'None'login'False}
 
def timmer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)  # my_max(1,2)
        stop_time = time.time()
        print('run time is %s' % (stop_time - start_time))
        return res
    return wrapper
 
def auth2(auth_type='file'):
    def auth(func):
        # print(auth_type)
        def wrapper(*args, **kwargs):
            if current_login['name'and current_login['login']:
                res = func(*args, **kwargs)
                return res
            if auth_type == 'file':
                name = input('username: ')
                password = input('password: ')
                if name == 'luchuan' and password == '123':
                    print('auth successfull')
                    res = func(*args, **kwargs)
                    current_login['name'= name
                    current_login['login'= True
                    return res
                else:
                    print('auth error')
            elif auth_type == 'sql':
                print('还他妈不会玩')
        return wrapper
    return auth
 
@timmer
@auth2(auth_type='file')  # @auth  #index=auth(index)
def index():
    print('welcome to inex page')
 
@auth2()
def home():
    print('welcome to home page')
 
# 调用阶段
index()
home()
原文地址:https://www.cnblogs.com/SHENGXIN/p/7496978.html