本文采取循序渐进的方式记录博主学习装饰器,并通过由简到繁的方式分析装饰器的优点和好处,欢迎交流讨论
import time
def f1():
print("this is function1!")
def f2():
print("this is function2!")
def print_time(fun):
print(time.time())
fun()
# 做法一:
print(time.time())
f1()
print(time.time())
f2()
# 做法二
print_time(f1)
print_time(f2)
import time
def f1():
print("this is function1!")
def f2():
print("this is function2!")
def decorator(fun):
def wrapper():
print(time.time())
fun()
return wrapper
decorator_f1 = decorator(f1)
decorator_f1()
decorator_f2 = decorator(f2)
decorator_f2()
仍然没有建立与原函数之间的关联
使用更加麻烦,甚至比上一种还麻烦
函数上一行加:@decorator
@[function],function为装饰器名称
import time
def decorator(fun):
def wrapper():
print(time.time())
fun()
return wrapper
@decorator
def f1():
print("this is function1!")
@decorator
def f2():
print("this is function2!")
f1()
f2()
使用装饰器解决了几个非常重要的问题
使用*args
import time
def decorator(fun):
def wrapper(*args):
print(time.time())
fun(*args)
return wrapper
@decorator
def f1(para1):
print("this is function1!")
print("parameter" + para1)
@decorator
def f2(para1, para2):
print("this is function2!")
print("parameter" + para1 + para2)
f1('1')
f2('1','2')
接收参数的语法:
明显多个参数具有普遍性
添加 **kw
注释,kw:kwy word
import time
def decorator(fun):
def wrapper(*args, **kw):
print(time.time())
fun(*args, **kw)
return wrapper
@decorator
def f1(para1):
print("this is function1!")
print("parameter" + para1)
@decorator
def f2(para1, para2):
print("this is function2!")
print("parameter" + para1 + para2)
def f3(para1, para2, **kw):
print("this is function2!")
print("parameter" + para1 + para2)
print(kw)
f1('1')
f2('1','2')
f3('1','2',a=1,b=2)
如何解决包含关键字参数的问题?
装饰器完整版:
def decorator(fun):
def wrapper(*args, **kw):
print(time.time())
fun(*args, **kw)
return wrappe
体现了什么思想,起到了什么作用?