装饰器

1、装饰器本质上是函数,为其它函数添加附加功能

2、原则上:1、不能修改被装饰的函数的源代码 2、不能修改被装饰的函数的调用方式

3、实现装饰器的知识储备:1、函数即“变量” 2、高阶函数 3、嵌套函数 所以,高阶函数+嵌套函数----》装饰器

4、解释函数即变量

5、装饰器自定义例子(装饰器不带参数)

import time


def timer(func):
    def deco(*args, **kwargs):
        start_time = time.time()
        res = func(*args, **kwargs)
        stop_time = time.time()
        print('此程序运行了%s秒' % (stop_time - start_time))
        return res
    return deco


@timer  # 相当于func = timer(func)
def func():
    time.sleep(3)

# func = timer(func)
# func()
func()
View Code

 

6、使用装饰器,可在自定义函数前加@decortor_name,相当于fun_name=decortor_name(fun_name),此处的目的就是为了不改变函数的调用方式。

7、装饰器带参数例子(终极版)

def auth(auth_type):
    def outerwrapper(func):
        def wrapper(*args, **kwargs):
            if auth_type == 'local':
                msg = '本地验证'
            elif auth_type == 'ldap':
                msg = '远程验证'
            print(msg)
            res = func(*args, **kwargs)
            return res
        return wrapper
    return outerwrapper


@auth(auth_type='local')  # 相当于home=wrapper
def home():
    print('In the home page')


@auth(auth_type='ldap')  # 相当于bbs=wrapper
def bbs():
    print('In the bbs page')


home()
bbs()
View Code

 

posted on 2018-10-24 00:01  Treelight  阅读(141)  评论(0编辑  收藏  举报