代码改变世界

装饰器

2018-04-17 16:09  今天我要学习  阅读(160)  评论(0)    收藏  举报

装饰器

#coding=utf-8

#定义一个装饰器:高阶函数+嵌套函数 = 装饰器#高阶函数:参数为函数,返回值为函数对象

#嵌套函数:有多个def,否则叫做函数的调用

import time

def decorator(fun):

    def calTime():

        start_time = time.time()

        fun()

        stop_time = time.time()

        print '该函数运行的时间是:%s秒'%(int(stop_time - start_time))

    return calTime

#被装饰的函数

@decorator  #test = decorator(test)

def test():

    print '我是被装饰的函数,请计算我运行的时间!' 

   time.sleep(3) #运行后试试test()

运行结果:

我是被装饰的函数,请计算我运行的时间!

该函数运行的时间是:3秒