Python的装饰器
(2022-04-05 09:33:36)| 分类: python |
1.
2.
3.
4.
5.
print_odds =
count_time_wrapper(print_odds)
然后可以直接print_odds()
6.
语法糖没有增加新功能,只是一种更方便的写法。
语法糖可以完全等价的转换为非语法糖的代码。
7.
8.
9.
10.
11.
12.
def count_time_wrapper(func):
func()
end_time = time.clock()
print("it takes {} s to find all odds".format(end_time - start_time))
return improved_func
@count_time_wrapper
def print_odds():
if __name__ == '__main__':
13.
@count_time_wrapper
def print_odds():
print_odds()
def print_odds():
print_odds = count_time_wrapper(print_odds)
print_odds()
14.
def count_odds(lim = 100):
for i in range(lim):
return cnt
同时修改辅助的闭包函数:
def count_time_wrapper(func):
ret = func()
end_time = time.clock()
print("it takes {} s to find all odds".format(end_time = start_time)
return ret
return improved_func
这样就解决了返回值的问题。
def count_time_wrapper(func):
ret = func((*args,**kwargs)
end_time = time.clock()
return ret
return improved_func
这样不仅返回值正常了,参数也正常了。这样就是一个完整的闭包函数。
15.一个主函数有多个装饰器:
@wrapper1
@wrapper2
等同于:
original_func = wrapper1(wrapper2(original_func))
original_func()

加载中…