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 decorator9 # 应用带参数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