装饰器

一、什么是python装饰器
python装饰器(函数):装饰函数或者类,对函数或类进行功能的扩展
标记符号:@函数名称
python装饰器:函数装饰器和类装饰器
装饰器的使用场景:
鉴权
日志
pytest
unittest
二、装饰函数
#装饰器函数的应用场景
def runTime(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        #执行原来函数的功能
        try:
            func(*args,**kwargs)
            info="无异常"
        except Exception as error:
            errorinfo="有异常,异常信息"+str(error)
        #执行扩展功能
        time.sleep(1)
        end_time = time.time()
        const = end_time - start_time
        print(f"统计{func.__name__}函数运行耗时{const}秒")
    return wrapper

@runTime
def  welcome_titen():
    print("欢迎来到Titen的园子")
@runTime
def function1(a,b):
    sum=0
    sum=a+b
    print(f"执行函数1代码,a+b={sum}")

  

三、装饰类
class Demo:
    def __init__(self,func):
        self._func=func

    #实例() 自动化执行__call__方法
    def __call__(self, *args, **kwargs):
        print("执行__call__方法")
        # 执行被装饰的函数功能
        self._func()
        # 扩展功能
        print(f"执行{self._func.__name__}扩展功能")
@Demo
def test():
    print("执行test函数")
@Demo
def test2():
    print("执行test2函数")
四、装饰器执行顺序

注:当被装饰的函数存在多个装饰器执行规则:最先执行最里面的装饰函数,最后执行最外层的装饰器函数(就近原则)

def a(func):
    def wrapper():
        func()
        print('a')
    return wrapper

def b(func):
    def wrapper():
        func()
        print('b')
    return  wrapper


def c(func):
    def wrapper():
        func()
        print('c')
    return wrapper

@c
@b
@a
def test3():
    print("执行test3函数")


>>>a b c

 

本质:装饰函数的调用了装饰器内置函数,装饰类调用了类的__call__方法。

 

 

  每篇一句:

  你还记得小时候说过的话么?

 

posted on 2022-01-14 00:31  Titen  阅读(22)  评论(0编辑  收藏  举报

导航