如何正确用装饰器

发布时间:2021-10-15 09:10:34 作者:iii
来源:亿速云 阅读:116

这篇文章主要讲解了“如何正确用装饰器”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何正确用装饰器”吧!

1. 问题

大概问题是这样,想要自定义一个Python装饰器,问我这样写装饰器行不行?如果不行,那又是为什么?

import datetime import time  def print_time(g):     def f():         print('开始执行时间')         print(datetime.datetime.today())                  g()                  print('结束时间')         print(datetime.datetime.today())     f()

下面使用 print_time装饰函数 foo:

@print_time def foo():     time.sleep(2)     print('hello world')

当调用 foo函数时,抛出如下异常:

foo()  --------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last) <ipython-input-27-c19b6d9633cf> in <module> ----> 1 foo()  TypeError: 'NoneType' object is not callable

所以,按照如上定义 print_time装饰器,肯定是不行的。

2. 为什么不行

要想明白为啥不行,首先要知道装饰器这个语法的本质。其实很简单,@print_time装饰foo函数等于:

foo = print_time(foo)

就是这一行代码,再也没有其他。

因为上面的 print_time 无返回值,所以赋值给 foo 函数后,foo 函数变为 None,所以当调用 foo() 时抛出 'NoneType'  object is not callable

这也就不足为奇了。

3. 应该怎么写

print_time 需要返回一个函数,这样赋值给 foo函数后,正确写法如下所示:

import datetime import time  def print_time(g):     def f():         print('开始执行时间')         print(datetime.datetime.today())                  g()                  print('结束时间')         print(datetime.datetime.today())     return f

装饰 foo:

@print_time def foo():     time.sleep(2)     print('hello world')

调用 foo ,运行结果如下:

foo()  开始执行时间 2021-04-02 22:32:49.114124 hello world 结束时间 2021-04-02 22:32:51.119506

一切正常

4. 装饰器好处

上面自定义print_time装饰器,除了能装饰foo函数外,还能装饰任意其他函数和类内方法。

装饰任意一个函数 foo2:

@print_time def foo2():   print('this is foo2')

装饰类内方法 foo3,需要稍微修改原来的print_time:

def print_time(g):     def f(*args, **kargs):         print('开始执行时间')         print(datetime.datetime.today())              g(*args, **kargs)              print('结束时间')         print(datetime.datetime.today())     return f

为类MyClass中foo3方法增加print_time装饰:

class MyClass(object):     @print_time     def foo3(self):         print('this is a method of class')

执行结果如下:

MyClass().foo3()  开始执行时间 2021-04-02 23:16:32.094025 this is a method of class 结束时间 2021-04-02 23:16:32.094078

以上就是装饰器的通俗解释,平时可以多用用,让我们的代码更加精炼、可读。

感谢各位的阅读,以上就是“如何正确用装饰器”的内容了,经过本文的学习后,相信大家对如何正确用装饰器这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. Python中装饰器怎么用
  2. Python装饰器decorator怎么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:怎么通过用户的编辑权限控制组策略对象控制对象

下一篇:Python标准库的很多初步进程是怎样的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》