装饰器变形记

装饰器前奏:

装饰器变形:

(1)第一种变形

(2)第二种变形

(3)第三种变形

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

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

 

带标志位的装饰器:

 

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

带参数的装饰器:

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/luchuangao/p/6842293.html