Python3装饰器

装饰器

    定义:本质是函数,装饰其他函数(就是为其他函数添加附加功能)

    原则:1、不能修改被装饰的函数的源代码

              2、不能修改被装饰的函数的调用方式

实现装饰器的知识储备:1、函数即“变量” 2、高阶函数 3、嵌套函数(在一个函数体内用def去申明一个新函数)

高阶函数+嵌套函数--》装饰器


内存回收机制:变量与函数的内存回收机制是一样的

实例如下:

def timer(func):
    def deco():
        func()
        print(3)
    return deco
@timer     # ---> test1 = timer(test1)
def test1():
    print(1)

@timer
def test2():
    print(2)

test1()
test2()
输出:
1
3
2
3

猜你喜欢

转载自blog.csdn.net/zhuisaozhang1292/article/details/79969549