python中的函数装饰器

我们在编写日常的开发过程中,代码中经常需要记录日志,比如编写一个函数,在函数的入口和出口需要记录函数的入参、出参和返回值等信息。如果我们用的是C++进行开发,就需要在函数的入口和该函数的出口都要添加日志记录的代码,比如:

 
  1. void TestFunciton()
  2. {
  3. FunctionStart();
  4. // do something
  5. FunctionComplete();
  6. }

其中FunctionStart和FunctionComplete分别为函数入口和出口信息添加日志的宏定义。这样的话,每个函数都需要添加类似的日志记录的代码,显得即多余又必须。
但是在python中,我们就可以避免这样的尴尬了,因为在python中我们有函数装饰器。那么什么是函数装饰器?又该怎么用呢?
简单点说,函数装饰器,就是一个可以修改其他函数功能的函数,来看下面的例子:

 
  1. def coding():
  2. return "I am coding"
  3. def start_work(func):
  4. print("Wait for work start time...")
  5. print(func())
  6. print("Work overtime...")
  7. start_work(coding)
  8. #output:Wait for work start time...
  9. # I am coding

函数start_work相当于对coding函数进行了封装,在执行coding函数前增加了等待工作开始和下班后加班的操作,这就已经是一个简单的函数装饰器了。我们稍微改造一下这个装饰器,让它更合理一些:

 
  1. def work_decorator(func):
  2. def working():
  3. print("Wait for work start time...")
  4. func()
  5. print("Work overtime...")
  6. return working
  7. def coding():
  8. print("I am coding")
  9. coding = work_decorator(coding)
  10. coding()
  11. #output:Wait for work start time...
  12. # I am coding
  13. # Work overtime...

进一步的,我们可以使用函数修饰符:

 
  1. def work_decorator(func):
  2. def working():
  3. print("Wait for work start time...")
  4. func()
  5. print("Work overtime...")
  6. return working
  7. @work_decorator
  8. def coding():
  9. print("I am coding")
  10. coding()

但是,此时如果我们输出coding.name,就会得到working,这是因为working替代了coding函数,重写了函数名,这并不是我们想要的结果,可以使用functools.wraps来解决这个问题:

 
  1. from functools import wraps
  2. def work_decorator(func):
  3. @wraps(func)
  4. def working():
  5. print("Wait for work start time...")
  6. func()
  7. print("Work overtime...")
  8. return working
  9. @work_decorator
  10. def coding():
  11. print("I am coding")

在回到我们一开始遇到的问题,如果使用函数装饰器就很好解决了:

 
  1. from functools import wraps
  2. def work_decorator(func):
  3. @wraps(func)
  4. def working():
  5. print("Function {0} entry".format(func.__name__))
  6. func()
  7. print("Function {0} return".format(func.__name__))
  8. return working
  9. @work_decorator
  10. def coding():
  11. print("I am coding")
  12. coding()
  13. #output:Function coding entry
  14. # I am coding
  15. # Function coding return
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

qzw405

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

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

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

打赏作者

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

抵扣说明:

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

余额充值