python - 装饰器

一、装饰器

装饰器:本质是函数,(装饰其他函数),就是位其他函数添加附加功能。

在Python里,装饰器(Decorator)是一种极简的调用高阶函数(higher-order function)的语法。Python里,装饰器(Decorator)就是一个函数,她接受另一个函数作为参数,然后在不直接修改这个函数的情况下,扩展该函数的行为,最终再将该函数返回。

原则:
1)不能修改被装饰的函数的源代码。 func1去修饰其他函数,那么func1的源代码不能修改。
2)不能修改被装饰函数的调用方式。

实现装饰器知识储备:
1)函数即变量
2)高阶函数
3)嵌套函数

高阶函数+嵌套函数 =》装饰器。

装饰器实例:

import time

# 手写一个装饰器
def timmer(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        func()
        stop_time = time.time()
        print ('the func run time is %s' %(stop_time - start_time))
    return wrapper

@timmer
def test1():
    time.sleep(3)
    print ('in the test1')

test1()

首先遵循上面的几个原则。
对于被装饰函数test1()来说,就如没有装饰器的函数一样。
扩展被装饰函数的行为。


函数体在内存中就是一堆字符串。

python - 装饰器_第1张图片
图片.png

函数就是变量,变量是有内存回收机制的,函数也就是了。

python解释器一解释到,那么内存中就存在了,就可以调用了。

python - 装饰器_第2张图片
图片.png

传递的函数,可以运行:

python - 装饰器_第3张图片
图片.png
python - 装饰器_第4张图片
图片.png
python - 装饰器_第5张图片
图片.png

可以函数内存地址加上()去调用函数。

python - 装饰器_第6张图片
图片.png

高阶函数的两个功能:

python - 装饰器_第7张图片
图片.png

函数的嵌套:

python - 装饰器_第8张图片
图片.png

装饰器。

import time

def test1():
    time.sleep(3)
    print ('in the test1')


def test2():
    time.sleep(2)
    print ('in the test2')

def deco(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print ('run time %s' % (stop_time - start_time))
    return wrapper


test1 = deco(test1)
test1()

@一个函数名

@timer 
def test1():
     xxxx

等价于:
test1 = timer(test1)

加了断点的话,运行,就使用debug运行。

你可能感兴趣的:(python - 装饰器)