装饰器常用方法
经典调用方法
#!/usr/bin/env python # -*- coding:utf-8 -*- # by wk import time import random ''' 一:编写函数,(函数执行的时间是随机的) ''' def my_random_time(func): def wrapper(*args, **kwargs): r_time = random.randint(0,5) print('函数将在%s秒后执行' %r_time) time.sleep(r_time) func(*args, **kwargs) return wrapper @my_random_time def random_func(): print('开始运行了') random_func()
装饰器带参数
#!/usr/bin/env python # -*- coding:utf-8 -*- # by wk ''' 三:编写装饰器,为函数加上认证的功能 ''' def login_func(choose_type='file'): def login_func2(func): def wrapper(*args, **kwargs): username = input('请输入用户名: ') password = input('请输入密码: ') if choose_type == 'file': with open('user.txt','r',encoding='utf-8') as user_r: read_str = user_r.readline() read_dict = eval(read_str) if read_dict['name'] == username and read_dict['password'] == password: func(*args, **kwargs) login_status = 'ok' else: print('登录失败') # return login_status return wrapper return login_func2 @login_func(choose_type='file') def user_login(): print('登录成功') user_login()
带参数方法2
#!/usr/bin/env python # -*- coding:utf-8 -*- # by wk my_dic={} def my_func(my_var): def wrapper(func): my_dic[my_var] = func return wrapper @my_func('select') def func1(): print('select') @my_func('insert') def func2(): print('insert') @my_func('update') def func3(): print('update') @my_func('delete') def func4(): print('delete') print(my_dic) my_dic['select']() my_dic['insert']() my_dic['update']() my_dic['delete']()
武老师写的装饰器
def Before(request,kargs): print('I am before') def After(request,kargs): print('I am After') def Filter(before_func,after_func): def outer(main_func): def wrapper(request,kargs): before_result = before_func(request,kargs) if(before_result != None): return before_result main_result = main_func(request,kargs) if(main_result != None): return main_result after_result = after_func(request,kargs) if(after_result != None): return after_result return wrapper return outer @Filter(Before,After) def index(request,kargs): print("I am index") index('w','k')