Python自学成才之路 使用函数作为装饰器

时间:2022-07-23
本文章向大家介绍Python自学成才之路 使用函数作为装饰器,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前面都是用类作为装饰器(传送门),主要是用类作为装饰器理解起来更容易。其实函数也可以用来做装饰器,因为函数本身就是可调用的,而且函数作为装饰器用得更多。同样函数作为装饰器可分为装饰器带有参数和不带参数。

第一种:不带参数的装饰器

不带参数的装饰器需要以函数作为参数,最后返回一个函数,如下所示:

def my_decorate(func):
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
    return wrapper


@my_decorate
def my_function(arg1):
    print('this is nmy_function : %s' %arg1)

my_function('hello')

输出:
this is nmy_function : hello

这个过程等价于 1.将my_function作为参数传入my_decorate函数中,返回wrapper函数 2.给wrapper传入参数并执行

wrapper = my_decorate(my_function)
wrapper('hello')

第二种:装饰器带参数

先看案例:

def my_decorate(params):
    print(params)
    def out_wrapper(func):
        def inner_wrapper(*args, **kwargs):
            func(*args, **kwargs)
        return inner_wrapper
    return out_wrapper


@my_decorate('hello my_decorate')
def my_function(arg1):
    print('this is nmy_function : %s' %arg1)

my_function('hello')

输出:
hello my_decorate
this is nmy_function : hello

其实很好理解,就是使用一个函数包住装饰器函数,这里可以理解为使用my_decorate包住装饰器函数out_wrapper,所以my_decorate(‘hello my_decorate’) 返回的是out_wrapper,最后out_wrapper作为my_function的装饰器。

这个过程等价于 1.传递参数给my_decorate函数并,返回out_wrapper函数 2.传递my_function给out_wrapper函数并执行,返回inner_wrapper函数 3.传递参数给inner_wrapper函数并执行

out_wrapper = my_decorate('hello my_decorate')
inner_wrapper = out_wrapper(my_function)
inner_wrapper('hello my_decorate')