Python 的 带参数的装饰器

等级 5239 次按键

这创建一个接受参数的装饰器。外部函数接受参数并返回实际的装饰器。

Python 代码

# 外部函数接受装饰器参数
1def repeat(times):
# 实际的装饰器函数接受函数
2 def decorator(func):
# 包装函数替换原始函数
3 def wrapper(*args, **kwargs):
# 执行函数times次
4 for _ in range(times):
# 调用原始函数并存储结果
5 result = func(*args, **kwargs)
# 返回最后的结果
6 return result
# 返回包装函数
7 return wrapper
# 返回装饰器
8 return decorator
9
# 应用带参数3的装饰器
10@repeat(3)
# 定义要被装饰的函数
11def greet(name):
# 打印问候消息
12 print(f"Hello, {name}!")
13
# 调用装饰后的函数,会打印3次
14greet("Alice")

运行结果

Hello, Alice!
Hello, Alice!
Hello, Alice!
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • (× 9
  • )× 9
  • *× 6
  • :× 5
  • "× 4
  • ,× 3
  • _× 1
  • !× 1
  • {× 1
  • }× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习