Python装饰器的使用详解

目录

1、函数装饰器

1.1、闭包函数

1.2、装饰器语法

1.3、装饰带参数的函数

1.4、被装饰函数的身份问题

1.4.1、解决被装饰函数的身份问题

1.5、装饰器本身携带/传参数

1.6、嵌套多个装饰器

2、类装饰器

装饰器顾名思义作为一个装饰的作用,本身不改变被装饰对象的原本功能,只是对被装饰对象扩展了额外的功能,装饰器分为两类:函数装饰器类装饰器

1、函数装饰器

说明:函数装饰器是一个函数接受另一个函数作为参数的函数,它包装了函数的行为,并返回包装后的函数。所以装饰器的目的是为了扩展函数的功能,而不是修改函数本身,装饰器器的本质就是闭包函数。下面说明一下什么是闭包函数:

1.1、闭包函数

闭包的定义:在函数嵌套的前提下,内部函数使用外部函数的变量,并且外部函数返回内部函数
我们把这个使用外部函数变量的内部函数称为闭包。

闭包函数的作用:变量在函数运行之后销毁,但有的时候需要这个函数的变量,这时候使用闭包函数解决。

闭包函数的三要素:

  • 1.实现函数嵌套
  • 2.内部函数使用外部函数的变量
  • 3.外部函数返回内部函数

我们来看一个示例:

def wrapper_hello(func: callable):
    def wrapper():
        print("this is start")
        func()
        print("this is end")

    return wrapper

def hello():
    print("hello world")

# 闭包函数的使用
hello_new = wrapper_hello(hello)
# 函数的调用
hello_new()

运行结果:

解释:
上面的代码中定义了两个函数,其中hello()函数是一个普通函数,它的功能是打印hello world。
我们来看看wrapper_hello()函数具体实现了什么功能:

  • 1.首先它的参数func是一个可调用对象。
  • 2.然后它的内部定义了一个函数wrapper(),并把wrapper对象作为返回值。
  • 3.wrapper()函数内部执行过程:
    • 先打印输出了“this is start”
    • 然后执行func()
    • 最后打印输出"this is end"

所以我们可以说wrapper_hello()函数扩展了hello()函数的功能,hello()原本实现的功能并没有改变。

1.2、装饰器语法

说明:Python提供了一种语法来定义装饰器。称为糖语法(通过@修饰目标函数), 它可以将修饰后函数赋值给修饰函数本身,所以调用函数时,还是直接调用,装饰器只是给函数增加额外的功能,本身并不改变函数功能和调用执行方式。
示例:

def wrapper_hello(func: callable):
    def wrapper():
        print("this is start")
        func()
        print("this is end")

    return wrapper

# 装饰器糖语法写法
@wrapper_hello
def hello():
    print("hello world")

# 还是正常的调用函数
hello()

# 调用等价于
# hello = wrapper_hello(hello)
# hello()

1.3、装饰带参数的函数

说明:因为Python不允许装饰器接受被装饰对象的参数,所以要想实现装饰带参数的函数,在装饰器内部函数中使用 *args 和 **kwargs 来实现。

示例:

def wrapper_hello(func: callable):
    def wrapper(*args, **kwargs):
        print("this is start")
        # 注意如果func函数有返回值,需要使用一个对象来接受返回值,不然func执行完成后就销毁了,也就得不到它原本的返回值。
        res = func(*args, **kwargs)
        print("fun执行结果:", res)
        print("this is end")
        return res

    return wrapper

# 装饰器糖语法写法
@wrapper_hello
def hello(name):
    return "hello world %s"%name

# 还是正常的调用函数
hello("Tom")

注意:要想获取目标函数的返回值结果,必须要在装饰器内部返回执行结果,否则无法获取执行的结果,原因是func函数执行完之后就会被销毁,所以需要在装饰器内部保存目标函数的执行结果。

1.4、被装饰函数的身份问题

说明:如果查看修饰后函数的名字,或者使用内置的help函数查看,发现被修饰函数的名字是wrapper。因为Python认为现在的函数是装饰器函数的内部函数。

示例:

def wrapper_hello(func: callable):
    def wrapper(*args, **kwargs):
        print("this is start")
        # 注意如果func函数有返回值,需要使用一个对象来接受返回值,不然func执行完成后就销毁了,也就得不到它原本的返回值。
        res = func(*args, **kwargs)
        print("fun执行结果:", res)
        print("this is end")
        return res

    return wrapper

# 装饰器糖语法写法
@wrapper_hello
def hello(name):
    return "hello world %s"%name

# 查看hello函数的名字
print(hello.__name__)
help(hello)

运行结果:

1.4.1、解决被装饰函数的身份问题

说明:可以使用functools.wraps装饰器解决这个问题,它的作用是保留原函数的信息。 这可以帮助我们在运行时获取原本对象的信息,比如函数的名字,参数等。

注:也可以显示使用wrapper.__name__ = func.__name__的方法实现

示例:

def wrapper_hello(func: callable):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("this is start")
        # 注意如果func函数有返回值,需要使用一个对象来接受返回值,不然func执行完成后就销毁了,也就得不到它原本的返回值。
        res = func(*args, **kwargs)
        print("fun执行结果:", res)
        print("this is end")
        return res

    # 等价于@functools.wraps(func)的作用
    # wrapper.__name__ =  func.__name__
    return wrapper

# 装饰器糖语法写法
@wrapper_hello
def hello(name):
    return "hello world %s"%name

# 查看hello函数的名字
print(hello.__name__)
help(hello)

运行结果:

1.5、装饰器本身携带/传参数

说明:为了更好地理解装饰器参数的必要性, 我们实现一个repeat装饰器,它接受一个数字作为输入。这个装饰器的功能是:重复执行目标函数给定的次数。

示例1:

import functools
def repeat(num_times):
    def inner_repeat(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for i in range(num_times):
                result = func(*args, **kwargs)
            return result

        return wrapper
    return inner_repeat

@repeat(num_times=3)
def hello(name):
    print('hello {}'.format(name))

hello('Tom')

示例2:

import functools
def repeat1(num_times):
    def repeat():
        def inner_repeat(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                for i in range(num_times):
                    result = func(*args, **kwargs)
                return result

            return wrapper
        return inner_repeat
    # 注意这里返回的内部repeat函数的调用
    return repeat()

@repeat1(num_times=3)
def hello(name):
    print('hello {}'.format(name))

hello('Tom')

执行结果都为以下结果:

解释:
装饰器执行原理:不管装饰器嵌套了多少层函数,执行顺序是从最外层的函数开始执行也就是repeat1函数,原因是理解为队列,遵循先进先出的原理,所以从最外层的函数先执行。
所以若要装饰器可以传参数最多只需要嵌套3层即可,再嵌套就显得多余和没有必要。
注意:

  • 1、装饰器函数多层嵌套,需要每层都要有返回值,即每层返回对应的函数名。
  • 2、函数括号的参数属于整个函数内部的“全局变量”,也就是不管函数内部嵌套了多少层函数,都可以使用这些变量

1.6、嵌套多个装饰器

说明:通过堆叠的方式将多个装饰器应用到一个函数上。 这些装饰器按照顺序从上到下开始执行

示例:

import functools
# 装饰器嵌套
def start_end(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('this is start')
        result = func(*args, **kwargs)
        print('this is end')
        return result

    return wrapper

def debug(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args_repr = [repr(a) for a in args]
        kwargs_repr = [f"{k} = {v!r}" for k, v in kwargs.items()]
        signature = ", ".join(args_repr + kwargs_repr)
        # print(signature)
        print(f"calling {func.__name__} ({signature})")
        result = func(*args, **kwargs)
        print(f" {func.__name__!r} returned {result!r}")
        return result

    return wrapper

def hello(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("这里是hello函数开始")
        result = func(*args, **kwargs)
        print("这里是hello函数结束")

    return wrapper

@start_end
@debug
@hello
def say_hello(name):
    res = f'hello {name}'
    print(res)
    return res

say_hello("张三")

运行结果:

解释:

从运行结果可以看出,多重装饰器的嵌套是从上至下开始执行的,但是并不是等一个装饰器执行完了再执行下一个,而是从第一个装饰器开始执行到目标函数停止继续寻找下一个装饰器执行,然后执行第二个装饰器同样执行到目标函数停止继续寻找下一个装饰器执行,按照该方式继续执行,直到执行到最后一个装饰器,才开始执行目标函数,然后层层返回到最外层。

执行原理:就是遵循的栈的先进后出原理。

注意:目标函数不管嵌套了多少层装饰器,目标函数有且仅执行一次。

2、类装饰器

说明:我们也可以使用类作为装饰器。 但是必须实现__call__()方法,目的是使我们的对象可调用。 类装饰器通常用于维护状态。

示例:我们记录函数被调用的次数。 __call__本质上和wrapper()方法是一样的。 它添加了一些功能,执行函数,并返回其结果。

注意:这里我们使用functools.update_wrapper()而不是functools.wraps()来保留我们的函数的信息。

示例:

import functools

class CountCallNums:
    def __init__(self, func):
        functools.update_wrapper(self,func)
        self.func = func
        self.count = 0

    def __call__(self, *args, **kwargs):
        self.count += 1
        print(f"函数{self.func.__name__} 被执行了 {self.count}次")
        return self.func(*args, **kwargs)


@CountCallNums
def hello():
    print("hello")

hello()
hello()

# 上面装饰器等价于
# hello = CountCallNums(hello)
# hello()
# hello()

print(hello.__name__)
help(hello)

运行结果:

  • 17
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
装饰器Python中一种强大的功能,允许在不修改原始函数的情况下,向函数添加额外的功能。装饰器使用@符号将其应用于函数。 一个装饰器函数通常具有以下形式: ```python def decorator(func): def wrapper(*args, **kwargs): # 添加额外的功能 return func(*args, **kwargs) return wrapper ``` 其中,`decorator`是装饰器函数本身,`wrapper`是内部函数,用于包装原始函数,并添加额外的功能。 装饰器可以应用于函数,类甚至是类的方法。通过在被装饰的函数或方法前使用装饰器函数,可以将装饰器应用于该函数或方法。 例如,引用中的代码展示了一个简单的装饰器模板,引用中的代码展示了一个使用装饰器实现函数计时器的例子。在这个例子中,`timec`是装饰器函数,`wrapper`是内部函数用于计算函数执行的时间。被`timec`装饰的函数`con_add`和`join_add`会在执行前后输出运行时间。 引用中的代码展示了一个包含关键字的装饰器的例子。在这个例子中,`decorator`是装饰器函数,`wrapper`是内部函数用于在执行被装饰的函数前后输出时间。被`decorator`装饰的函数`f`接受两个位置参数和任意个关键字参数,并在执行前后输出相应的信息。 总之,装饰器Python中一种强大的功能,可以用于给函数或方法添加额外的功能,而不需要修改原始函数的代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python装饰器使用](https://blog.csdn.net/belong_to_you/article/details/111003741)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python装饰器使用](https://blog.csdn.net/qq_43830639/article/details/95247941)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值