Python进阶-初探函数之装饰器
装饰器
1.开放封闭原则
通常情况下,软件一旦上线就应该遵循开放封闭原则,即对修改封闭、对扩展开放
扩展开放需遵循两个原则:
1)不修改源代码
2)不修改原函数的调用方式
2.装饰器
器指的是工具,装饰指的是为被装饰对象添加新功能;即不修改源代码和调用方式的基础上为被装饰函数添加新功能
注意:装饰器和被装饰对象可以是任意可调用的对象
装饰器模板: ''' def outer(func): def wrapper(*args,**kwargs): res = func(*args,**kwargs) return res return wrapper '''
3.无参装饰器
import time def outer(func): def wrapper(*args,**kwargs): strt_time = time.time() res = func(*args,**kwargs) stop_time = time.time() print('index run time is %s' %(stop_time-strt_time)) return res return wrapper @outer def index(): time.sleep(1) print('welcome to index page...') return 'ahah' @outer def home(name): time.sleep(2) print('home page...',name) # 闭包函数实现 # 不改变原函数的调用方式和源代码 index() home('zhang')
4.多个装饰器叠加使用
import time db_file = '锁定用户.txt' def timer(func): def wrapper(*args,**kwargs): strt_time = time.time() res = func(*args,**kwargs) stop_time = time.time() print('index run time is %s' %(stop_time-strt_time)) return res return wrapper def auth(func): def wrapper(*args,**kwargs): tag = True while tag: user_inp = input('输入用户名>>').strip() pwd = input('输入密码>>') with open(r'%s' % db_file,'rt',encoding='utf-8') as f: for line in f: user_info = line.strip('\n').split(',') if user_inp == user_info[0] and pwd == user_info[1]: print('logging successful...') tag = False break else: print('logging false,please tay again...') res = func(*args,**kwargs) return res return wrapper # @timer # @auth # 当timer装饰在前时,统计的时间是auth + index的运行时间 # @auth # @timer # 当timer装饰在后时,统计的时间是index的运行时间 @timer @auth def index(): time.sleep(1) print('welcome to index page...') return 'ahah' index()
5.含参装饰器
import time current_user={ 'username':None, # 'login_time':None } def auth(engine): # engine='file' def auth2(func): # func=index def wrapper(*args,**kwargs): if engine == 'file': if current_user['username']: print('已经登陆过了') res=func(*args,**kwargs) return res uname=input('用户名>>: ').strip() pwd=input('密码>>: ').strip() if uname == 'egon' and pwd == '123': print('登陆成功') current_user['username']=uname res=func(*args,**kwargs) return res else: print('用户名或密码错误') elif engine == 'mysql': print('基于MyQL的认证') elif engine == 'ldap': print('基于LDAP的认证') return wrapper return auth2 @auth('ldap') #@auth2 #index=auth2(index) #index=wrapper def index(): time.sleep(1) print('welcome to index page') return 10 index() # wrapper()

浙公网安备 33010602011771号