Python 中的装饰器是一个非常强大的功能,它允许你在不修改函数本身代码的情况下,对函数的行为进行扩展或修改。装饰器本质上是一个函数,它接受一个函数作为参数,返回一个新的函数,并且新函数的行为与原函数不同。
1. 简单的装饰器示例
def uppercase(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
@uppercase
def say_hello(name):
return f"hello, {name}"
print(say_hello("Alice")) # Output: HELLO, ALICE
在这个例子中:
uppercase 函数是一个装饰器,它接受一个函数 func 作为参数。
uppercase 函数返回一个新的函数 wrapper,wrapper 函数会在调用原函数 func 后,将结果转换成大写形式。
使用 @uppercase 语法,我们可以将 say_hello 函数"装饰"为大写输出。
2. 装饰器的一些常见用途
添加日志记录: 在函数执行前后添加日志输出。
缓存函数结果: 使用记忆化技术缓存函数的计算结果。
访问控制: 检查用户的权限,决定是否允许访问某个函数。
性能分析: 测量函数的执行时间。
错误处理: 捕获并处理函数中的异常。
3. 装饰器也可以是带参数的,这样可以让装饰器更加灵活
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
result = ""
for _ in range(n):
result += func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say_hello(name):
return f"hello, {name}"
print(say_hello("Alice")) # Output: hello, Alice hello, Alice hello, Alice
在这个例子中,repeat 是一个接受参数的装饰器工厂函数。它返回一个装饰器函数 decorator,decorator 函数会创建一个 wrapper 函数,wrapper 函数会重复调用原函数 n 次并拼接结果。
总的来说,Python 的装饰器是一个非常强大的功能,它可以帮助我们编写更加优雅、可重用和可维护的代码。掌握装饰器的使用技巧是每个 Python 开发者都应该具备的技能之一。