2025-09-20
Python
00
请注意,本文编写于 94 天前,最后修改于 94 天前,其中某些信息可能已经过时。

目录

什么是装饰器?
装饰器的基本结构
使用装饰器
装饰器的实际应用
1. 记录函数调用日志
2. 计算函数执行时间
3. 权限验证
类装饰器
示例
内置装饰器
@staticmethod 和 @classmethod
@property
多个装饰器
示例
总结

Python 装饰器(decorator)是一种强大的工具,可以在不修改函数或类定义的情况下扩展其功能。它广泛应用于日志记录、性能计时、权限验证等场景。本文将详细介绍 Python 装饰器的概念、用法及其背后的机制,并通过实例展示装饰器的实际应用。

什么是装饰器?

装饰器本质上是一个高阶函数,它接受一个函数作为参数并返回一个新的函数。装饰器用于在不改变原函数代码的前提下,动态地增加或修改其功能。

装饰器的基本结构

python
def decorator(func): def wrapper(*args, **kwargs): # 在调用原函数之前可以执行一些操作 result = func(*args, **kwargs) # 在调用原函数之后可以执行一些操作 return result return wrapper

使用装饰器

python
@decorator def my_function(): print("Hello, World!") my_function()

上述代码等价于:

python
def my_function(): print("Hello, World!") my_function = decorator(my_function) my_function()

装饰器的实际应用

1. 记录函数调用日志

python
def log_decorator(func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__} with arguments {args} and {kwargs}") result = func(*args, **kwargs) print(f"Function {func.__name__} returned {result}") return result return wrapper @log_decorator def add(a, b): return a + b add(5, 3)

输出:

Calling function add with arguments (5, 3) and {} Function add returned 8

2. 计算函数执行时间

python
import time def timing_decorator(func): def wrapper(*args, **kwargs): start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print(f"Function {func.__name__} executed in {end_time - start_time:.4f} seconds") return result return wrapper @timing_decorator def compute(): time.sleep(2) compute()

输出:

Function compute executed in 2.0023 seconds

3. 权限验证

python
def check_permission(user): def decorator(func): def wrapper(*args, **kwargs): if user == "admin": return func(*args, **kwargs) else: print("Permission denied") return wrapper return decorator @check_permission("admin") def delete_file(): print("File deleted") delete_file()

输出:

File deleted

类装饰器

除了函数装饰器,Python 还支持类装饰器。类装饰器是实现了 __call__ 方法的类,它允许在类实例化时执行装饰操作。

示例

python
class LogDecorator: def __call__(self, func): def wrapper(*args, **kwargs): print(f"Calling function {func.__name__}") return func(*args, **kwargs) return wrapper @LogDecorator() def greet(name): print(f"Hello, {name}!") greet("Alice")

输出:

Calling function greet Hello, Alice!

内置装饰器

Python 提供了一些内置装饰器,如 @staticmethod@classmethod@property

@staticmethod@classmethod

python
class MyClass: @staticmethod def static_method(): print("This is a static method") @classmethod def class_method(cls): print("This is a class method") MyClass.static_method() MyClass.class_method()

@property

python
class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, value): if value < 0: raise ValueError("Radius cannot be negative") self._radius = value circle = Circle(5) print(circle.radius) circle.radius = 10 print(circle.radius)

多个装饰器

一个函数可以同时被多个装饰器修饰,装饰器的执行顺序是从内到外。

示例

python
def decorator1(func): def wrapper(*args, **kwargs): print("Decorator 1") return func(*args, **kwargs) return wrapper def decorator2(func): def wrapper(*args, **kwargs): print("Decorator 2") return func(*args, **kwargs) return wrapper @decorator1 @decorator2 def my_function(): print("Hello, World!") my_function()

输出:

Decorator 1 Decorator 2 Hello, World!

总结

装饰器是 Python 中强大且灵活的工具,可以在不修改原函数或类的情况下动态地扩展其功能。通过本文的介绍,希望你对 Python 装饰器有了更深入的理解,并能在实际编程中灵活运用装饰器来提高代码的可读性和可维护性。

如果你有任何疑问或建议,欢迎在评论区留言。

本文作者:Dewar

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!