1.9 装饰器

1. 装饰器定义

不能修改被装饰函数的源代码,不能修改被装饰函数的调用方式,为其他函数添加其他功能

2. 使用高阶函数模拟装饰器

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
def timer(func):
    start_time = time.time()
    func()
    print '函数执行时间为', time.time() - start_time
def test():
    print '开始执行test'
    time.sleep(3)
    print 'test执行结束'
timer(test)
'''
开始执行test
test执行结束
函数执行时间为 3.00332999229
'''

3. 计算运行时间装饰器

import time
def timer(func):   #timer(test1)  func=test1
    def deco(*args,**kwargs):
        start_time = time.time()
        func(*args,**kwargs)      #run test1
        stop_time = time.time()
        print("running time is %s"%(stop_time-start_time))
    return deco
@timer     # test1=timer(test1)
def test1():
    time.sleep(3)
    print("in the test1")
test1()

4. 装饰器使用场景

授权:装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中

日志:在记录日志的地方添加装饰器

缓存:通过装饰器获取缓存中的值

猜你喜欢

转载自www.cnblogs.com/lihouqi/p/12664238.html
1.9
今日推荐