python 装饰器在类中的使用
原创
©著作权归作者所有:来自51CTO博客作者小嘉欣008的原创作品,请联系作者获取转载授权,否则将追究法律责任
示例:
1 # encoding="utf-8"
2
3 import os
4 import time
5 from functools import wraps
6
7
8 class Demo(objecct):
9 def __init__(self):
10 pass
11
12 def print_run_time(func):
13 @wraps(func)
14 def wrapper(self, *args, **kw):
15 start_time = time.time()
16 result = func(self, *args, **kw)
17 end_time = time.time()
18 # print("函数的运行时间(s):{}".format(end_time - start_time))
19 self.write_to_file.info_to_file("函数的运行时间(s):{}".format(end_time - start_time))
20 # print("函数的运行时间(ms):{}".format(float(end_time - start_time) * 1000.0))
21 self.write_to_file.info_to_file("函数的运行时间(ms):{}".format(float(end_time - start_time) * 1000.0))
22 return result
23
24 return wrapper
25
26 @print_run_time
27 def add_sum(self, a, b):
28 sum = a + b
29 return sum
30
31
32