装饰器
约 609 字大约 2 分钟
2026-08-17
装饰器的本质
装饰器本质上是一个接受函数作为参数并返回新函数的高阶函数:
def my_decorator(func):
def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper
# 下面的代码
def say_hello():
print("Hello!")
say_hello = my_decorator(say_hello)
# 等效于
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# 函数执行前
# Hello!
# 函数执行后装饰器是一个可调用对象,接收一个可调用对象,返回任意对象。但为了保证程序能正常运行,通常返回另一个可调用对象来替代原对象。
多个装饰器叠加
可以同时使用多个装饰器,执行顺序为从下到上:
@decorator_a
@decorator_b
def func():
pass
# 等效于:
# func = decorator_a(decorator_b(func))作业
前置知识: 本章作业中会用到
time模块的两个功能:
time.time():返回当前时间的时间戳(一个浮点数)time.sleep(seconds):让程序暂停执行指定的秒数例如:
import time start = time.time() time.sleep(1) elapsed = time.time() - start print(f"耗时: {elapsed} 秒")
一、实现timer装饰器
import time
def timer(func):
# 你的代码
pass
@timer
def slow_function():
time.sleep(1)
return "Done"
slow_function()
# 输出:slow_function 执行时间: 1.0012 秒二、实现wraps装饰器
实现wraps装饰器,用于不改变函数的名称和注释
# 实现wraps装饰器,用于不改变函数的名称和注释
def wraps(func):
# 你的代码
pass
def my_decorator(func):
@wraps(func)
def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper
@my_decorator
def say_hello():
"""打招呼"""
print("Hello!")
say_hello()
# 输出:
# 函数执行前
# Hello!
# 函数执行后
print("name", say_hello.__name__)
print("doc", say_hello.__doc__)三、实现repeat装饰器
def repeat(n):
# 你的代码
pass
@repeat(3)
def say_hello(s):
print(s)
say_hello(1) # 输出: 1 1 1四、实现cache装饰器
编写一个装饰器 cache,缓存函数的计算结果。当使用相同的参数调用函数时,直接返回缓存的结果:
def cache(func):
# 你的代码
pass
@cache
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(35)) # 应该快速返回结果提示: 使用字典存储参数到结果的映射。
五、实现to_dict装饰器
编写一个类装饰器 to_dict,自动为类生成 to_dict 方法,该方法可以将对象转换为字典
def to_dict(cls):
# 你的代码
pass
@to_dict
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p.to_dict()) # 应该输出: {"x":3, "y":4}