小陆同学

python 中文名:蟒蛇,设计者:Guido van Rossum

导航

python--装饰器的常见使用

装饰器验证接口响应时长

from time import time
def print_execute_time(func):
    def wrapper(*args, **kwargs):
        start = time()
        func_return = func(*args, **kwargs)
        end = time()
        print('函数:{name},执行时间:{time}'.format(name=func.__name__,time=end-start))
        return func_return
    return wrapper
@print_execute_time
def test1():
    for i in range(100):
        pass
if __name__ == '__main__':
    test1()

装饰器验证权限

def is_superuser(fun):
    def wrapped(name,*args,**kwargs):
        if name == '张三':
            return fun()
        else:
            return False
    return wrapped
# 调用装饰器:@+装饰器名
@is_superuser
def hello():
    return "hello world"
if __name__ == '__main__':
    print(hello('张三1'))

 

posted on 2020-08-28 21:32  小陆同学  阅读(224)  评论(0编辑  收藏  举报