研读代码时遇到了python装饰器,所以要搞懂它,这一过程加深了自己对于函数定义与函数调用的体会
一. 装饰器本质就是个函数,用来增加被装饰函数的功能.
二. 使用装饰器的巨大优势:不改变被装饰函数的调用方式; 不修改被装饰函数的源代码
三. 无参数装饰器使用两层嵌套; 带参数装饰器使用三层嵌套
下面举两个简单的例子,为了笔记的方便,定义装饰器函数时我用了三种命名:decorator_para; decorator; wrapper,这样有助于记忆
无参数装饰器
为函数加上计时功能
写两层嵌套装饰器函数时牢记两点:向decorator传入被装饰函数名; decorator返回wrapper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import time def decorator(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) total = time.time() - start print('函数%s的执行时间为:%s秒' % (func.__name__,total)) return wrapper
@decorator #相当于 tesla = decorator(tesla) def tesla(price='95W'): time.sleep(2) print('鸥翼门真帅气,不过价格挺刺激:%s' % price)
tesla()
|
带参数装饰器
为函数加上计时功能, 可以选择显示方式:default方式是不保留小数;normal方式保留两位小数
写三层嵌套装饰器函数时牢记三点:向decorator_para中传入装饰器要用的参数;向decorator传入被装饰函数名; decorator返回wrapper; decorator_para返回decorator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
import time
def decorator_para(count_type): def decorator(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) total = time.time() - start if count_type == 'default': print('函数%s的执行时间为:%s秒' % (func.__name__,total)) elif count_type == 'normal': print('函数%s的执行时间为:%.2f秒' % (func.__name__,total)) return wrapper return decorator @decorator_para('normal') def tesla(price='95W'): time.sleep(2) print('鸥翼门真帅气,不过价格挺刺激:%s' % price)
tesla()
|