Python学习笔记--装饰器

装饰器可以不修改函数内部代码而添加新的功能:

 1 #!/usr/bin/python3
 2 # -*- coding:utf-8 -*-
 3 '''
 4 Author:flyinghappy
 5 Date:2020.02.13
 6 Note:装饰器学习
 7 '''
 8 import time
 9 '''不修改函数内部代码,添加新的功能,下面的装饰器函数的功能是原函数执行前后的时间显示'''
10 def decorator_funtion(func):
11     def inner(*args,**kwargs):
12         print(f"start at {time.strftime('%X')}")
13         result=func(*args,**kwargs)
14         print(f"end at {time.strftime('%X')}")
15         return result
16     return inner
17 @decorator_funtion
18 def function(arg):
19     '''最原始的函数'''
20     print('本函数的任务是打印:',arg)
21     time.sleep(2)
22 '''
23 原来函数function增加函数执行时的时间显示功能。
24 上面用到装饰器函数了。
25 '''
26 if __name__ == '__main__':
27     function('我是原始函数!')

执行结果如下:

猜你喜欢

转载自www.cnblogs.com/flyinghappy/p/12372826.html