一、装饰器:
本质就是函数,功能是为其他函数添加附加功能
二、装饰器原则:
1.不修改被修饰函数的源代码
2.不修改被修饰函数的调用方式
三、装饰器框架:
1.装饰器=高阶函数+函数嵌套+闭包
高阶函数:
函数接收的参数是一个函数名
函数的返回值是一个函数名
满足上述条件任意一个,都可称之为高阶函数
闭包:
如果一个函数定义在另一个函数的作用域内,并且引用了外层函数的变量,则该函数称为闭包。闭包是Python所支持的一种特性,它让在非global scope定义的函数可以引用其外围空间中的变量,这些外围空间中被引用的变量叫做这个函数的环境变量。环境变量和这个非全局函数一起构成了闭包
#装饰器基本框架:无参、无返回值、无功能 def timer(func): def wrapper(): func() return wrapper
#装饰器加参数、加返回值 def timmer(func): def wrapper(*args,**kwargs): #加上参数,可以是任何数据类型(函数嵌套) res=func(*args,**kwargs) return res #加上返回值 return wrapper()
#装饰器:加参数,加返回值,加功能 import time def timmer(func): def wrapper(*args,**kwargs): starttime=time.time() res=func(*args,*kwargs) stoptime=time.time() print('程序运行时间为:%.2fs'%(stoptime-starttime)) return res return wrapper @timmer #@timmer相当于test=timmer(test) def test(x,y): time.sleep(1) z=x+y print('%d+%d='%(x,y),z) return z test(3,4) #输出结果: #3+4= 7 #程序运行时间为:1.00s
四、装饰器练习
user_info=[ {'name':'alice','passwd':'774411','point':123}, {'name':'mike','passwd':'789123','point':1100}, {'name':'xiaoxiao','passwd':'223344','point':567}, {'name':'sherly','passwd':'112233','point':79} ] user_shopping_car=[ {'name':'alice','goods':['衣服','鞋子','包包']}, {'name':'mike','goods':['便利贴','杯子','盆']}, {'name':'xiaoxiao','goods':['本子','笔','橡皮擦']}, {'name':'sherly','goods':['鼠标','键盘','手机']} ] current={'username':None,'loginstatus':False} def auth(func): def wrapper(*args,**kwargs): if current['username'] and current['loginstatus']: res = func(*args, **kwargs) return res else: username=input('input the username:') passwd=input('input the passwd:') for infolist in user_info: if infolist['name']==username and infolist['passwd']==passwd: current['username']=username current['loginstatus']=True res=func(*args,**kwargs) return res else: print('用户名或者密码错误') return wrapper @auth def index(): print('\033[44;1m欢迎来到XX主页\033[0m') @auth def shopping_car(username): for s in user_shopping_car: if s['name']==current['username']: gds=s['goods'] print('\033[44;1m%s的购物车里有:%s\033[0m' % (current['username'],gds)) @auth def reward_points(username): for i in user_info: if i['name']==current['username']: pnt=i['point'] print('\033[44;1m%s的会员积分有%d\033[0m'%(current['username'],pnt)) def mainpr(): print('\033[41;1m欢迎来到XX网站\033[0m') while True: choice = input('1:首页\n2:购物车\n3:积分\n4:退出\n选择你要进入的页面:') if not choice: continue elif not choice.isdigit(): continue elif int(choice)==1: index() elif int(choice)==2: shopping_car(current['username']) elif int(choice) == 3: reward_points(current['username']) elif int(choice) == 4: print('\033[41;1m欢迎下次光临\033[0m') break else: continue mainpr()
学习资料来源:
https://www.cnblogs.com/linhaifeng/articles/6140395.html