Python装饰器核心是函数作为一等公民和闭包机制,通过@语法在不修改原函数代码的情况下为其添加新功能,如日志、权限控制、缓存等,提升代码复用性和可维护性。

Python装饰器,说白了,就是一种特殊函数,它能接收一个函数作为输入,然后给这个函数增加一些额外功能,最终返回一个全新的函数。它就像给你的老朋友穿上了一件新衣服,朋友还是那个朋友,但现在他可能更酷、更强大了,而且这一切都发生在不改变朋友本身代码的前提下。用起来很方便,一个
@
编写一个Python装饰器,核心在于理解函数作为一等公民的特性以及闭包的概念。最基础的装饰器,通常是一个接收函数、定义一个内部包装函数、然后返回这个包装函数的高阶函数。
我们先从一个最简单的例子开始。假设我们想在每次调用某个函数之前和之后都打印一些信息,但又不想每次都手动加
import functools
def log_calls(func):
"""
这是一个简单的装饰器,用于记录函数被调用的信息。
"""
@functools.wraps(func) # 这一行很重要,它能保留原函数的元信息,比如函数名、文档字符串等。
def wrapper(*args, **kwargs):
print(f"--- 函数 '{func.__name__}' 即将被调用 ---")
# 执行原函数
result = func(*args, **kwargs)
print(f"--- 函数 '{func.__name__}' 调用完毕,返回值为: {result} ---")
return result
return wrapper
# 现在,我们用这个装饰器来装饰一个函数
@log_calls
def add(a, b):
"""一个简单的加法函数。"""
print(f"正在执行 add({a}, {b})")
return a + b
@log_calls
def greet(name, greeting="Hello"):
"""向指定的人打招呼。"""
print(f"正在执行 greet('{name}', '{greeting}')")
return f"{greeting}, {name}!"
# 调用被装饰的函数
print("调用 add(5, 3):")
sum_result = add(5, 3)
print(f"add 函数的最终结果是: {sum_result}\n")
print("调用 greet('Alice'):")
greet_result = greet("Alice")
print(f"greet 函数的最终结果是: {greet_result}\n")
print("调用 greet('Bob', greeting='Hi'):")
greet_result_hi = greet("Bob", greeting="Hi")
print(f"greet 函数的最终结果是: {greet_result_hi}\n")
# 如果没有 @log_calls 语法糖,手动装饰是这样的:
# original_add = add
# add = log_calls(original_add)
# print(add(1, 2))在这个例子里,
log_calls
func
wrapper
wrapper
func
func
log_calls
wrapper
@log_calls
add
add = log_calls(add)
add
log_calls
wrapper
立即学习“Python免费学习笔记(深入)”;
functools.wraps
__name__
__doc__
__module__
wrapper
add.__name__
wrapper
add
在我看来,理解Python装饰器的核心,主要抓住两点:函数是“一等公民”和闭包。
首先,Python中的函数是“一等公民”(First-Class Citizen)。这意味着函数可以像普通变量一样被赋值给其他变量,可以作为参数传递给其他函数,也可以作为其他函数的返回值。正是因为这个特性,我们才能把一个函数(被装饰的函数)传给另一个函数(装饰器),让装饰器对它进行操作。
其次,也是更关键的一点,是闭包(Closure)。当我们定义
log_calls
wrapper
log_calls
func
log_calls
wrapper
log_calls
wrapper
func
所以,当Python解释器看到
@log_calls
add
log_calls(add)
log_calls
add
func
wrapper
add
add
log_calls
wrapper
add(5, 3)
wrapper(5, 3)
wrapper
add
整个过程巧妙地实现了在不修改原函数代码的情况下,为其添加新功能,这在很多场景下都非常有用,比如日志、权限控制、性能测量等等。
实际开发中,装饰器简直是“万金油”,能优雅地解决很多跨领域、重复性的问题。它避免了代码的重复,让业务逻辑更聚焦。
日志记录与调试 (Logging & Debugging): 这是最常见的用途。我们经常需要知道哪个函数在什么时候被调用了,传入了什么参数,返回了什么结果,或者执行了多久。一个通用的日志装饰器能完美解决这些需求,而不需要在每个函数内部都写一堆
logging
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def log_and_time(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logging.info(f"Calling {func.__name__} with args: {args}, kwargs: {kwargs}")
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
logging.info(f"{func.__name__} finished in {end_time - start_time:.4f}s. Result: {result}")
return result
return wrapper
@log_and_time
def complex_calculation(x, y):
time.sleep(0.1) # 模拟耗时操作
return x * y + 10
complex_calculation(10, 20)权限校验与认证 (Authentication & Authorization): 在Web应用中,很多视图函数都需要检查用户是否已登录,或者是否有足够的权限来访问某个资源。把这些检查逻辑封装成装饰器,能让视图函数专注于处理业务逻辑,而不是权限验证。
def requires_admin(func):
@functools.wraps(func)
def wrapper(user, *args, **kwargs):
if not user.is_authenticated:
raise PermissionError("User not logged in.")
if not user.is_admin:
raise PermissionError("User does not have admin privileges.")
return func(user, *args, **kwargs)
return wrapper
class User:
def __init__(self, name, authenticated=False, admin=False):
self.name = name
self.is_authenticated = authenticated
self.is_admin = admin
@requires_admin
def delete_user_data(current_user, user_id):
print(f"Admin '{current_user.name}' deleting data for user {user_id}")
return True
# try:
# admin_user = User("Alice", authenticated=True, admin=True)
# delete_user_data(admin_user, 123)
# guest_user = User("Bob", authenticated=True, admin=False)
# delete_user_data(guest_user, 456)
# except PermissionError as e:
# print(e)缓存 (Caching): 对于那些计算成本高昂且结果相对稳定的函数,我们可以用装饰器来缓存其返回值。当函数再次被相同的参数调用时,直接返回缓存结果,避免重复计算。
from functools import lru_cache
@lru_cache(maxsize=None) # Python内置的LRU缓存装饰器
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# 第一次计算会比较慢
print(fibonacci(30))
# 第二次计算(相同参数)会非常快,因为结果已被缓存
print(fibonacci(30))重试机制 (Retry Mechanism): 当调用外部服务或执行可能失败的操作时,我们可能需要自动重试几次。一个重试装饰器可以优雅地处理这种场景。
import time
import random
def retry(max_attempts=3, delay=1):
def decorator_retry(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {attempt} failed: {e}")
if attempt < max_attempts:
time.sleep(delay)
raise Exception(f"Function {func.__name__} failed after {max_attempts} attempts.")
return wrapper
return decorator_retry
@retry(max_attempts=5, delay=0.5)
def unstable_api_call():
if random.random() < 0.7: # 70%的几率失败
raise ConnectionError("Simulated API connection error.")
return "Data fetched successfully!"
# print(unstable_api_call()) # 尝试调用,可能会重试几次参数验证 (Argument Validation): 在函数内部对参数进行类型或值检查,可以用装饰器来集中处理,保持函数体的简洁。
这些例子只是冰山一角,装饰器在Web框架(如Flask、Django的路由装饰器)、ORM(如SQLAlchemy的事件监听)、以及各种库中都扮演着重要角色,极大地提高了代码的复用性和可维护性。
带参数的装饰器,相比不带参数的,多了一层嵌套。这其实是理解装饰器更深一步的关键。
当装饰器本身需要接收参数时,它就不能直接返回
wrapper
wrapper
import functools
def repeat(num_times):
"""
一个带参数的装饰器,让被装饰的函数重复执行指定次数。
`num_times` 是装饰器自身的参数。
"""
def decorator_repeat(func): # 这一层是真正的装饰器,它接收被装饰的函数
@functools.wraps(func)
def wrapper(*args, **kwargs): # 这一层是包装函数,它执行原函数
print(f"--- 函数 '{func.__name__}' 将重复执行 {num_times} 次 ---")
results = []
for i in range(num_times):
print(f" 执行第 {i+1} 次...")
result = func(*args, **kwargs)
results.append(result)
print(f"--- 函数 '{func.__name__}' 执行完毕 ---")
# 通常只返回最后一次执行的结果,或者根据需求返回所有结果
return results[-1] if results else None
return wrapper
return decorator_repeat # 装饰器函数返回的是真正的装饰器
@repeat(num_times=3) # 这里 num_times=3 就是装饰器的参数
def say_hello(name):
print(f"Hello, {name}!")
return f"Hello result for {name}"
print("调用 say_hello('Charlie'):")
final_result = say_hello("Charlie")
print(f"say_hello 函数的最终结果是: {final_result}\n")
@repeat(num_times=2)
def calculate_power(base, exp):
res = base ** exp
print(f"{base}^{exp} = {res}")
return res
print("调用 calculate_power(2, 3):")
power_result = calculate_power(2, 3)
print(f"calculate_power 函数的最终结果是: {power_result}\n")技巧和注意事项:
多一层嵌套: 最直观的变化就是多了一层函数嵌套。外层函数
repeat
num_times
decorator_repeat
decorator_repeat
func
执行时机:
@repeat(num_times=3)
repeat(num_times=3)
repeat
decorator_repeat
decorator_repeat
say_hello
say_hello = decorator_repeat(say_hello)
functools.wraps
functools.wraps(func)
wrapper
func
wrapper
参数传递: 装饰器参数(如
num_times
decorator_repeat
wrapper
类作为装饰器: 除了函数,类也可以作为装饰器。如果一个类实现了
__call__
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func) # 类似 functools.wraps
self.func = func
self.num_calls = 0
def __call__(self, *args, **kwargs):
self.num_calls += 1
print(f"函数 '{self.func.__name__}' 已被调用 {self.num_calls} 次")
return self.func(*args, **kwargs)
@CountCalls
def say_whee():
print("Whee!")
# say_whee() # 第一次调用
# say_whee() # 第二次调用类装饰器在需要维护状态(如上面的调用次数)时非常方便,因为状态可以直接存储在实例属性中。带参数的类装饰器也同样需要多一层嵌套,即外层函数返回一个类实例。
理解这些,就能更灵活地运用装饰器,为你的Python代码注入更多“魔力”和可维护性。
以上就是Python怎么编写一个装饰器_Python装饰器原理与实战开发的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号