函数装饰器

函数装饰器

不过尔尔 15 2023-12-03

介绍

装饰器就是一个闭包,装饰器是闭包的一种应用。

装饰器是用于拓展原函数功能的一种函数,它的返回值也是一个函数,使用装饰器的好处是在不用更改原函数代码的前提下给原函数增加新的功能。

分类

1,无参装饰器

 from functools import wraps
 ​
 def wrapper(func):
     @wraps(func)
     def inner(*args, **kwargs):
         print("调用hi函数之前执行")
         result = func(*args, **kwargs)
         print("调用hi函数之后执行")
         return result
 ​
     return inner
 ​
 @wrapper
 def hi():
     print("hello")
 ​
 hi()

输出:

 调用hi函数之前执行
 hello
 调用hi函数之后执行

2,有参装饰器

 from functools import wraps
 ​
 def decorator(value):
     def wrapper(func):
         @wraps(func)
         def inner(*args, **kwargs):
             print(f"执行hi函数之前打印===={value}====")
             result = func(*args, **kwargs)
             print("执行hi函数之后")
             return result
 ​
         return inner
 ​
     return wrapper
 ​
 @decorator("我被打印了")
 def hi():
     print("hello")
 ​
 hi()

输出:

 执行hi函数之前打印====我被打印了====
 hello
 执行hi函数之后

3,@wraps作用

原因:被装饰后的函数已经是一个新的函数了,它的函数名及属性等,都与原函数不同。

方法:Python提供了@wraps装饰器来消除这种情况。

4,使用方法

在被装饰函数的上方加上@装饰器函数名(示例中的hi为被装饰函数,wrapperdecorator为装饰器函数)