Python 装饰器快速指南
Python 装饰器快速指南
装饰器是 Python 中一个强大的功能,它允许你在不修改原函数代码的情况下,为其添加额外的功能。这在实际开发中非常有用,比如日志记录、性能监控、权限校验等。下面将简要介绍装饰器的基本概念和使用方法。
什么是装饰器
装饰器本质上是一个函数,它接收一个函数作为参数,并返回一个新的函数。使用装饰器可以为原函数添加额外的功能,而不需要修改原函数的代码。
基础装饰器
示例代码
def my_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
输出结果
Before the function is called.
Hello!
After the function is called.
带参数的装饰器
如果需要为装饰器添加参数,可以使用嵌套函数。例如:
示例代码
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(num_times=3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
输出结果
Hello, Alice!
Hello, Alice!
Hello, Alice!
保留原函数信息
使用 functools.wraps 可以保留原函数的名称和文档字符串等信息。
示例代码
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("Before the function is called.")
return func(*args, **kwargs)
return wrapper
@my_decorator
def say_hello():
"""A function that says hello."""
print("Hello!")
print(say_hello.__name__) # 输出: say_hello
print(say_hello.__doc__) # 输出: A function that says hello.
类装饰器
装饰器也可以通过类来实现,需要定义 __call__ 方法。
示例代码
class MyDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("Before the function is called.")
return self.func(*args, **kwargs)
@MyDecorator
def say_hello():
print("Hello!")
say_hello()
输出结果
Before the function is called.
Hello!
总结
装饰器是 Python 中一个非常强大的工具,它可以帮助你以一种非常优雅的方式为函数添加额外的功能。通过掌握装饰器的基本用法和一些进阶技巧,你可以在实际开发中更高效地利用装饰器,写出更简洁、更优雅的代码。

浙公网安备 33010602011771号