P47 函数装饰器

        在P42-P45中我们提到,对于嵌套函数,可以在外部函数中直接调用内部函数;在P46闭包函数中我们知道可以将内部函数作为返回值;那么我们思考一下,是否可以将函数作为参数传递到另一个函数中呢?

def myfunc():
    print('正在调用myfunc....')
def report(func):
    print('主人,我要调用函数了....')
    func()
    print('主人,我调用完函数啦,快夸夸我')
report(myfunc)

        我们设计一个时间管理大师程序,来计算传入函数的运行时间:

import time
def time_master(func):
    print('Ready for run the procedure')
    start = time.time() #获取初始时间戳
    func()
    stop = time.time() #获取结束时间戳
    print('End the procedure')
    print(f'The procedure expend {stop-start} 秒')

def myfunc():
    time.sleep(2) #让程序等待2秒钟运行
    print('Hello World')

time_master(myfunc)

 

        如果我们想知道任何一个目标函数的运行时间,那么我们每次都需要显示的调用time_master函数。如何在调用目标函数时自动调用time_master函数呢?

import time
def time_master(func):
    def call_func():
        print('Ready for run the procedure')
        start = time.time() #获取初始时间戳
        func()
        stop = time.time()
        print('End the procedure')
        print(f'The procedure expend {stop-start} 秒')
    return call_func

def myfunc():
    time.sleep(2)
    print('Hello World')

myfunc = time_master(myfunc)

myfunc()

 

         可看到,我们使用了 闭包函数 和 拿函数当参数 这俩个办法,实现了调用目标函数时自动调用time_master函数。我们将同时使用这俩个办法糅合成一个语法糖,将 myfun = time_master(myfunc) 写为 @time_master 放在 def myfun 上面,称为装饰器(Decorators)。上述代码段可写成:

import time
def time_master(func):
    def call_func():
        print('Ready for run the procedure')
        start = time.time() #获取初始时间戳
        func()
        stop = time.time()
        print('End the procedure')
        print(f'The procedure expend {stop-start} 秒')
    return call_func

@time_master
def myfunc():
    time.sleep(2)
    print('Hello World')

myfunc()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

汪小涵不记谱、

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值