这样用装饰器,为什么不行?

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
复制代码

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

以上就是本次分享的所有内容,想要了解更多欢迎前往公众号:Python 编程学习圈,每日干货分享

猜你喜欢

转载自juejin.im/post/7103027937678458911
今日推荐