将一个已经存在的函数包装成一个新函数,这就象“装修”一样。装饰器接收一个函数作为参数,并返回一个新的函数。这个新函数可以是原始函数的简单包装,也可以是在原始函数执行前后添加额外功能的函数。
在Python中,@
符号被用作装饰器(Decorator)的语法。装饰器是一种特殊的函数,它允许你修改或增强其他函数或方法的功能,而无需修改这些函数或方法的代码本身。
装饰器的基本使用
装饰器的基本语法如下:
@decorator
def function():
# 函数体
这里,@decorator
是将 decorator
这个装饰器应用于 function
函数。这等价于将 function
作为参数传递给 decorator
函数,并将 decorator
函数的返回值(通常是一个新函数)赋值给 function
变量名。
示例
假设我们有一个简单的函数,我们想在每次调用它之前和之后,各打印一条消息(包装,可将打印语句修改成强大的功能模块):
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
def say_hello():
print("Hello!")
# 使用装饰器
say_hello = my_decorator(say_hello)
# 现在 say_hello 实际上是 wrapper 函数
say_hello()
使用 @
符号修改上述程序,可以使程序更加简洁和直观:
#调用装饰前的函数
say_hello()
#定义装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
#对函数进行装饰
@my_decorator
def say_hello():
print("Hello!")
#调用装饰后的函数
say_hello()
- 装饰器可以应用于函数和类(作为类的元类使用)。
- 装饰器可以带有参数,这种情况下,你需要定义一个返回装饰器的外层函数。
- 装饰器可以接受任意数量的位置参数、关键字参数、
*args
和**kwargs
,这取决于你想要装饰的函数签名。 - 使用装饰器时,要注意函数签名(即参数名和默认参数值)保持不变,但函数的内部实现和行为可以被修改。
装饰器是Python中一个非常强大和灵活的特性,它允许程序员在不修改原有代码结构的情况下,为函数或方法添加新的功能。
专业化
专业的人做专业的事:你是房间的主人,你只需要使用好房间,房间的装修承包给了专业的公司。依这个思路,装饰器由库实现,你只管实现业务。如是上述程序就分裂为两部分。
1、装饰器开发人员写:
#定义装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
如,func()为数据库操作(业务上的事),那操作之前需要与数据库建立连接,操作完需要拆除连接(在程序中以两个print语句代表),这就是装饰器的事。
2、业务应用开发人员写:
#导入装饰器
from ... import ... #含上述my_decorator
#定义业务处理函数
#并对其进行装饰
@my_decorator
def say_hello():
print("Hello!") #这里是业务处理功能
#调用装饰后的函数
say_hello()
这样,你作为业务应用开发人员就不必关心装饰器的实现了,实现业务功能是你的主业。
函数的参数哪儿传?
上述func函数没有参数,若有参数,则是这样的:
def my_decorator(func): #---接收函数名
def wrapper(*args, **kwargs): #---接收函数的参数
print("Something is happening before the function is called.")
result = func(*args, **kwargs)
print("Something is happening after the function is called.")
return result
return wrapper
@my_decorator
def say_hello(name): #---有参数的函数
print(f"Hello, {name}!")
# 调用装饰后的函数
say_hello("Bob")
具体见程序中的注释。
嵌套装饰器
嵌套装饰器允许你组合多个装饰器的功能,为函数添加多重特性。比如,结合日志记录和性能测试:
#已定义两装饰器log_decorator、timer_decorator
#如下对complex_operation进行装饰(两层装饰)
@log_decorator
@timer_decorator
def complex_operation():
# 某些复杂的计算
pass
#调用装饰后的函数
complex_operation()
参数化的装饰器
有时,你可能需要根据不同的情况调整装饰器的行为,这就是参数化装饰器的用武之地:
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hi():
print("Hi!")
say_hi() # 输出 "Hi!" 三次