装饰器
装饰器:本质就是函数,功能是为其他函数添加附加功能
原则:
1.不修改被修饰函数的原代码
2.不修改被修饰函数的调用方式
装饰器 = 高阶函数 + 函数嵌套 + 闭包
import time def timeer(fun): def wrapper(*args,**kwargs): begin = time.time() res = fun(*args,**kwargs) #接收被装饰函数的返回值 over = time.time() print("程序运行时间%s" % (over - begin)) return res return wrapper @timeer #等价于 test=timmer(test) def test(name,age,gentor): time.sleep(3) print("函数运行结束") print('这个姓名是【%s】,年纪是【%s】,性别是【%s】'%(name,age,gentor)) return '这是函数返回值' @timeer def test1(name,age): time.sleep(3) print('这个姓名是【%s】,年纪是【%s】'%(name,age)) res = test("jack",18,'女') res_1 = test1("rose",19) print(res)
说明:
装饰器固定用法:
def test(fun):
def wrapper()
fun()
return wrapper
装饰器中闭包的使用方法:
装饰器方法中带上一个参数,供下面的方法一起使用,代码如下:
user_list = [ {'name': 'alxe', 'pwd': '1234'}, {'name': 'alxe1', 'pwd': '1234'}, {'name': 'alxe2', 'pwd': '1234'}, ] current_dic = {'username': None, 'login': False} def auth(auth_type = 'filedb'): def auth_fun(fun): def wrapper(*args, **kwargs): if auth_type == 'lsap': print('现在的认证方式是%s' % auth_type) if current_dic['username'] and current_dic['login']: res = fun(*args, **kwargs) return res username = input('请输入用户名:').strip() passwd = input('请输入密码:').strip() for i in user_list: if i['name'] == username and i['pwd'] == passwd: current_dic['username'] = username current_dic['login'] = True res = fun(*args, **kwargs) return res else: print("输入的用户名或密码错误") elif auth_type == 'filedb': print("现在的认证方式是%s"%auth_type) res = fun(*args, **kwargs) return res else: print("现在的认证方式鬼也不知道") res = fun(*args, **kwargs) return res return wrapper return auth_fun @auth(auth_type='lsap') #auth_fun = auth_type='lsap'--->@auth_fun---> home=auth_fun(home) def home(name): print('欢迎%s来到京东主页' % (name)) @auth(auth_type='ss') def shopping(name): print('%s购物车里有冰激凌'%(name)) home('jack') shopping('小钱')
auth_type就是装饰器中的闭包使用
装饰器包含:
返回值、闭包、高阶函数、嵌套
浙公网安备 33010602011771号