Python_装饰器
装饰器:修改(增添)函数功能的函数
@函数
1 def home(func): # 这就是一个装饰器 2 def inner(arg): 3 print('hello,') 4 func(arg) 5 return inner 6 @home # 装饰器关键字 7 def eye(name): 8 print('see,%s'% name) 9 10 #eye = home(eye)("vera") # 相当于@home 11 eye("vera")
结果:
hello,
see, Vera
代码详解:
若eye里有返回值,则把func(name)改为 return func(name)
1 def home(func): 2 3 def inner(*args, **kwargs): # 动态参数用于传入多个参数,这里表示tuple与字典形式的参数都可以传入 4 5 print('hello,') 6 return func(*args, **kwargs) # return用于返回mouse里的return值 7 return inner 8 9 10 @home 11 def eye(name, passwd): 12 print('see, %s, or, %s' % (name, passwd)) 13 14 15 16 @home 17 def mouse(name, passwd): # 可传入两个参数 18 19 print('speak, %s,or ,%s' % (name, passwd)) 20 return 3 21 22 23 # eye = home(eye) 24 h = mouse('hi', 'over') 25 eye('yee', passwd="ha") # 传入两个不同的参数 26 print(h) # 用于测试是否可以打印mouse里的返回值
结果:
hello, speak, hi,or ,over hello, see, yee, or, ha 3
复杂装饰器:(了解)一个装饰器框架,可以直接传入多个函数作为一个装饰器
1 def Before(request, kargs): 2 print('before') 3 return 3 4 5 def After(request, kargs): 6 print('after') 7 8 9 def complex(before_func, after_func): 10 11 def come(main_func): 12 13 def on(request, kargs): 14 15 before_result = before_func(request, kargs) 16 if(before_result != None): 17 print('传入函数有返回值') 18 return before_result 19 20 main_result = main_func(request, kargs) 21 if(main_result != None): 22 print('传入函数有返回值') 23 return main_func 24 25 after_result = after_func(request, kargs) 26 if(after_result != None): 27 print('传入函数有返回值') 28 return after_func 29 30 return on 31 return come 32 33 @complex(Before, After) 34 def show(request, kargs): 35 print('hello') 36 37 38 show('Vera', 'Presly')
结果:
Vera
hello
Presley
装饰器传参:
def one(flag_1=True,flag_2=True): def two(func): def three(arg): if flag_1: if flag_2: print('******') else: print('flag_2') print('my_flag_1') else: print('nononconono') func(arg) return three return two @one(flag_1=False) def eye(inner): print(inner) eye('sdafjdkaljsklajkf')
装饰器:装饰器是我们用@语法糖来标识的,用来加工被装饰函数的一种语法