[Python]装饰器
# 简介 装饰器就是使用创建一个闭包函数,在闭包函数内调用目标函数。 可以达到不改动目标函数的同时,增加额外的功能。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def outer(func): def inner(): print('开始延迟') func() print('延迟结束') return inner def yanchi(): import random import time seconds = random.randint(1,5) print(f"延迟{seconds}秒") time.sleep(seconds) ''' fn = outer(yanchi) fn() ''' # 糖写法 @outer # 定义在目标函数之上,和第14行功能一致 def yanchi_2(): import random import time seconds = random.randint(1,5) print(f"延迟{seconds}秒") time.sleep(seconds) yanchi_2() 开始延迟 延迟2秒 延迟结束
来自 初然忆作者主页
在原博客阅读全文 (新标签页打开)
以上内容来自博客订阅源,版权归原作者。热度统计站内详情页访问。
登录后,加入这场讨论。
登录参与