python-装饰器
装饰器
# 定义:本质是函数,装饰其他函数,就是为其他函数添加附加功能
# 开放封闭原则
# 开放 : 对扩展是开放的
# 封闭 : 对修改是封闭的
作用:在不修改函数源代码情况下,增加功能
# 装饰器不能使用在递归函数上
代码实现
1 #被装饰函数无参数时 2 def a(): 3 pass 4 def b(): 5 pass 6 def c(): 7 pass 8 9 def decorator(func): 10 print("Start",str(func)) 11 return func 12 13 a = decorator(a) 14 b = decorator(b) 15 c = decorator(c) 16 17 a() 18 b() 19 c()
1 #当被修饰函数有参数时 2 def a(arg): 3 print(arg) 4 pass 5 def b(arg): 6 pass 7 def c(arg): 8 pass 9 10 def decorator(func): 11 def wrapper(*args,**kwargs): 12 print("Start", str(func)) 13 return func(*args,**kwargs) 14 return wrapper 15 16 17 a = decorator(a) 18 b = decorator(b) 19 c = decorator(c) 20 21 arg = "----" 22 a(arg) 23 b(arg) 24 c(arg) 25 26 """ 27 def wrapper(func): 28 def inner(*args,**kwargs): 29 print('在被装饰的函数执行之前做的事') 30 ret = func(*args,**kwargs) 31 print('在被装饰的函数执行之后做的事') 32 return ret 33 return inner 34 """
1 #当装饰器中有参数时 2 def decorator(*arg_of_decorator,**kwargs_of_decorator): 3 def log(func): 4 def wrapper(*args,**kwargs): 5 print("Start", str(func)) 6 return func(*args,**kwargs) 7 return wrapper 8 return log 9 10 arg = "----" 11 12 @decorator() 13 def a(arg): 14 print(arg) 15 pass 16 17 @decorator(arg) 18 def b(arg): 19 pass 20 21 @decorator(arg) 22 def c(arg): 23 pass 24 25 26 a(arg) 27 b(arg) 28 c(arg)
1 #多个装饰器装饰一个函数 2 def wrapper1(func): 3 def inner1(): 4 print('wrapper1 ,before func') 5 ret = func() 6 print('wrapper1 ,after func') 7 return ret 8 return inner1 9 10 def wrapper2(func): 11 def inner2(): 12 print('wrapper2 ,before func') 13 ret = func() 14 print('wrapper2 ,after func') 15 return ret 16 return inner2 17 18 def wrapper3(func): 19 def inner3(): 20 print('wrapper3 ,before func') 21 ret = func() 22 print('wrapper3 ,after func') 23 return ret 24 return inner3 25 26 @wrapper3 27 @wrapper2 28 @wrapper1 29 def f(): 30 print('in f') 31 return '哈哈哈' 32 33 print(f())
1 from functools import wraps 2 ''' 3 functools.wraps 则可以将原函数对象的指定属性复制给包装函数对象, 4 默认有 __module__、__name__、__doc__,或者通过参数选择 5 ''' 6 def wrapper(func): #func = holiday 7 @wraps(func) 8 def inner(*args,**kwargs): 9 print('在被装饰的函数执行之前做的事') 10 ret = func(*args,**kwargs) 11 print('在被装饰的函数执行之后做的事') 12 return ret 13 return inner 14 15 @wrapper #holiday = wrapper(holiday) 16 def holiday(day): 17 '''这是一个放假通知''' 18 print('全体放假%s天'%day) 19 return '好开心' 20 21 print(holiday.__name__) 22 print(holiday.__doc__) 23 ret = holiday(3) #inner 24 print(ret)