Python学习笔记6:装饰器

装饰器

装饰器就是以闭包的形式在不修改源代码的情况下添加新的功能,写装饰器的大题思路为先将实现的功能以及被装饰的程序封装成wrapper函数,然后用闭包的方法为封装成的函数添加func外部作用于实现此装饰器可以给不同的函数调用

一下为模拟网页运行,并为网页添加用户登录以及计算加载时间装饰器

import time
import random

# 计时功能装饰器
def timmer(func):
    # func = index

    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print(stop_time - start_time)
    return wrapper


# 用户登入功能装饰器
def auth(func):
    # func() = index()
    def deco():
        username = input('name:').strip()
        password = input('password:').strip()
        if username == 'rdw' and password == '123':
            func()
    return deco


@auth # 使用@为程序index()添加装饰器
@timmer  # index = timmer(index)
def index():
    time.sleep(random.randrange(1, 5))
    print('welecome to index page')

index()
posted @ 2017-06-19 23:24  戴维德  阅读(131)  评论(0编辑  收藏  举报