Python 装饰器是一种非常有用的特性,它允许你修改或增强函数或方法的行为,而无需修改函数的代码。装饰器常用于日志记录、认证、授权、缓存等方面。
装饰器基础
装饰器是一个接受函数作为参数并返回另一个函数的函数。以下是一个简单的装饰器示例:
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()
在上面的代码中,my_decorator
是一个装饰器,它接收 say_hello
函数作为参数,并返回一个新的 wrapper
函数。当我们调用 say_hello()
时,实际上是在调用 wrapper()
。
装饰器参数
装饰器可以接受参数。以下是一个带有参数的装饰器示例:
def decorator_with_args(number):
def my_decorator(func):
def wrapper(*args, **kwargs):
print("Decorator received the number: {}".format(number))
return func(*args, **kwargs)
return wrapper
return my_decorator
@decorator_with_args(42)
def say_hello(name):
print("Hello, {}!".format(name))
say_hello("Alice")
在这个例子中,decorator_with_args
接收一个参数 number
,并将其传递给装饰器内部函数 my_decorator
。当 my_decorator
被应用到一个函数上时,它会打印出 number
。
使用装饰器
装饰器通常用于增强函数或方法的行为。以下是一些常见的装饰器用途:
- 日志记录:记录函数执行前后的信息。
- 认证和授权:检查用户是否有权限执行某个操作。
- 缓存:缓存函数的结果,以避免重复计算。
扩展阅读
想要了解更多关于 Python 装饰器的信息,可以阅读以下教程:
[center][https://cloud-image.ullrai.com/q/Python_Documentation/](Python Documentation)[/center]