0513装饰器

一、装饰器

  装饰器实际上就是函数。

  装饰器的语法:

装饰器以@开头,接着是装饰器函数的名字可选的参数,紧跟着装饰器声明的是被修饰的函数装饰函数的可选参数

Demo:

@outer

  1、执行outer函数,将index作为参数传递

  2、将outer的返回值,重新赋值给index

def outer(func):
    def inner(a1,a2):
        print("123")
        ret = func(a1,a2)
        print("456")
        return ret
    return inner

@outer
def index(a1,a2):
    print("费劲")
    return a1 + a2
m = index(1,2)
print(m)

装饰器的执行流程:

装饰器的执行流程1、代码从上到下执行
2、将def outer(func)函数整体读取到内存中,不做任何处理
3、遇到@outer
    *执行outer函数,将index作为参数传递
    *将outer函数的返回值重新赋值给index
4、将被装饰的函数作为参数传递给outer函数==>def outer()
5、读到def inner(a1,a2),inner函数中并没有任何对inner的调用,所以inner函数的内部并不执行任何操作(直接放到内存当中)
6、执行return inner操作将outer的返回值从新赋值给index(此时的index函数,相当于inner函数)
7、此时执行def inner(a1,a2)函数
8、打印123
9、执行ret = func(a1,a2)这里的func相当于原来的index函数,根据@的特性这里要执行最初的index函数将"费劲"打印出来
10、将return a1 + a2返回给ret
11、执行打印456
12、将ret返回给他的调用者func也就是index并打印出来m = 3 

动态展示装饰器的运行过程

 

原文地址:https://www.cnblogs.com/mosson0816/p/5488713.html