Python装饰器

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12228953.html

给函数添加一些相应的功能,但是又不想影响函数的主业务功能,可以通过装饰器来实现。

e.g. 统计函数的执行时间

装饰函数

import time

def timer(func):
    def wrapper():
        start_time = time.time()
        func()
        stop_time = time.time()
        print('start time: %s, stop time: %s, running time: %s sec' %(start_time, stop_time, stop_time - start_time))
    return wrapper

被装饰的函数

@timer
def test():
    time.sleep(3)

Output

Summary

Python的装饰器相当于Spring中的AOP。

原文地址:https://www.cnblogs.com/agilestyle/p/12228953.html