python 装饰器在类中的使用

示例:

 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 Demo().add_sum(10, 20)

 

posted @ 2022-07-28 14:59  小嘉欣  阅读(409)  评论(0编辑  收藏  举报