本文会记录在开发中常遇到的Python装饰器经常用到的场景和代码示例
1. 函数运行时间
def get_running_time(func):
"""
装饰器,计算函数的运行时间
"""
def call_func(*args, **kwargs):
func_name = str(func.__name__)
print("start " + func_name)
start_time = time.time()
ret = func(*args, **kwargs)
end_time = time.time()
run_time = end_time - start_time
print(func_name + ', start time is' + str(start_time) +
' and end time is ' +
str(time.time()) + ' total cost ' + str(run_time) + 's')
return ret
return call_func
@get_running_time
def save_area_data(self):
sql = """ SELECT * FROM user """
pass
````