logo

🧪 装饰器

⏱️ 25-30 min📊 Advanced
main.py
Costs 1 credit
加载编辑器中...
输出 Output执行成功
# 运行代码后,输出将显示在这里
# 按 Ctrl+Enter 快速运行
Terminal (Simulated)Install commands are simulated only, no real network requests
$

Step 1: 理解装饰器原理

装饰器是“函数包装器”:不改原函数源码,也能在前后注入行为。

底层逻辑:
你传入原函数 func,返回包装函数 wrapper
后续调用其实执行的是 wrapper,它内部再调用原函数。

你的任务

  1. 创建函数 my_decorator(func)
  2. 内部定义 wrapper() 函数
  3. wrapper 中先输出 "Before",再调用 func(),最后输出 "After"
  4. 返回 wrapper
  5. 测试:定义 say_hello() 输出 "Hello!",用装饰器包装并调用

Self-Check List

  • 理解装饰器的基本结构

Transfer Template

def my_decorator(func):
    def wrapper():
After completing this step, you should be able to independently explain and reproduce this concept, then apply it to similar problems.

验证清单 (0/0)