python中的无参装饰器和有参装饰器
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python中的无参装饰器和有参装饰器,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含6950字,纯文字阅读大概需要10分钟。
内容图文
python中的无参装饰器和有参装饰器
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
装饰器特点:
1>.开放封闭原则,即对扩展是开放的,对修改时封闭的;
2>.装饰器本质可以是任意可调用的对象,被装饰的对象也可以是任意可调用对象;
3>.装饰器的功能是在不修改被装饰器对象源代码以及被装饰器对象的调用方式的前提下为其扩展新功能;
4>.装饰器本质是函数,(即装饰其他函数)就是为其他函数添加附加功能。
一.典型装饰器案例
1 # !/usr/bin/env python 2 # _*_coding:utf-8_*_ 3 # @author :yinzhengjie 4 # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 # EMAIL:y1053419035@qq.com 6 7 # 装饰器的语法:在被装饰对象的正上方的单独一行,@装饰器名字 8 import time 9 import random 10 11 def RunTime(TheCaller): #定义装饰器12def MyCaller(): 13 start_time = time.time() 14 TheCaller() 15 stop_time=time.time() 16print(‘run time is %s‘ %(stop_time-start_time)) 17return MyCaller 1819#被装饰函数20 @RunTime #等效于index=RunTime(index)21def index(): 22 time.sleep(random.randrange(2,4)) #可以在1-3秒钟(不包括4秒哟)随机睡眠指定范围的时长。23print(‘welecome to INDEX page‘) 2425 @RunTime #home=RunTime(home)26def home(): 27 time.sleep(random.randrange(1,2)) 28print(‘welecome to HOME page‘) 2930 index() #MyCaller()31home() 3233343536#以上代码执行结果如下:37welecome to INDEX page 38 run time is 2.0000088214874268 39welecome to HOME page 40 run time is 1.0006351470947266
二.多个装饰器案例展示
1 # !/usr/bin/env python 2 # _*_coding:utf-8_*_ 3 # @author :yinzhengjie 4 # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 # EMAIL:y1053419035@qq.com 6 7 # 装饰器的语法:在被装饰对象的正上方的单独一行,@装饰器名字 8 import time 9 import random 10 from functools import wraps 1112def RunTime(TheCaller): #定义装饰器+13 @wraps(TheCaller) #可以让用户查看帮助信息的时候查看其自己的源代码定义的帮助信息。14def MyCaller(*args,**kwargs): 15‘‘‘16 Runtime‘s help information 17‘‘‘18 start_time = time.time() 19 res = TheCaller(*args,**kwargs) 20 stop_time=time.time() 21print(‘run time is %s‘ %(stop_time-start_time)) 22return res 2324return MyCaller 2526def NewAddAuth(TheCaller): 27def Auth(*args,**kwargs): 28 name=input(‘username: ‘) 29 password=input(‘password: ‘) 30if name == ‘yinzhengjie‘and password == ‘123‘: 31print(‘login successful‘) 32 res = TheCaller(*args,**kwargs) 33return res 34else: 35print(‘login error‘) 36return Auth 3738#被装饰函数39# @NewAddAuth40 @RunTime #等效于index=RunTime(index),装饰器的执行顺序是自下而上。41def Index(): 42‘‘‘43 Index‘s help information 44‘‘‘45 time.sleep(random.randrange(2,4)) #可以在1-3秒钟(不包括4秒哟)随机睡眠指定范围的时长。46print(‘welecome to INDEX page‘) 47return"yinzhengjie"4849 @RunTime #home=RunTime(home)50def Home(name): 51‘‘‘52 Home‘s help information 53‘‘‘54 time.sleep(random.randrange(1,2)) 55print(‘welecome to %s HOME page‘%(name)) 56return 666 5758 res1 = Index() #MyCaller()59 res2 = Home("尹正杰") 60print("Index return :%s"%(res1)) 61print("Home return :%s"%(res2)) 62# print(help(Index))63# print(Index().__doc__)6465666768#以上代码执行结果如下:69welecome to INDEX page 70 run time is 3.000018835067749 71welecome to 尹正杰 HOME page 72 run time is 1.0001890659332275 73 Index return :yinzhengjie 74 Home return :666
三.有参装饰器
1 # !/usr/bin/env python 2 # _*_coding:utf-8_*_ 3 # @author :yinzhengjie 4 # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 # EMAIL:y1053419035@qq.com 6 7 ‘‘‘ 8 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登陆成功一次,后续的函数都无需再验证。 9 ‘‘‘ 10 11 12 # user_dic = { 13 # ‘yinzhengjie‘:‘123‘, 14 # ‘Golang‘:"666", 15 # ‘Python‘:"888", 16 # } 17 # 18 # with open("user.db","w",encoding="utf-8")as f: 19 # f.write(str(user_dic)) 20 21 22 23 24 db_path = "user.db"2526 login_dic ={ 27‘user‘:None, 28"status":False, 29} 3031def Decorator(AuthType="file"): 32def auth(func): 33def wrapper(*args, **kwargs): 34if AuthType == "file": 35if login_dic[‘user‘] and login_dic[‘status‘]: 36 res = func(*args, **kwargs) 37return res 38 username = input("username:") 39 password = input("password:") 40 with open(db_path, "r", encoding="utf-8")as f: 41 user_dic = eval(f.read()) 42if username in user_dic and password == user_dic[username]: 43print(‘login successful‘) 44 login_dic[‘user‘] = username 45 login_dic[‘status‘] = True 46 res = func(*args, **kwargs) 47return res 48else: 49print(‘login error‘) 50elif AuthType == "ldap": 51print("LDAP认证方式") 52elif AuthType == "MySQL": 53print("MySQL认证方式") 54else: 55print("其他认证方式") 56return wrapper 57return auth 5859@Decorator() 60def Index(): 61print("Welcome to Index!") 6263 @Decorator(AuthType="MySQL") 64def home(name): 65print("Welecome %s to home page!"%name) 6667Index() 68 home("尹正杰") 6970717273#以上代码执行结果如下:74username:yinzhengjie 75 password:123 76login successful 77Welcome to Index! 78 MySQL认证方式
四.小试牛刀
1. 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登陆成功一次,后续的函数都无需再验证。
1 # !/usr/bin/env python 2 # _*_coding:utf-8_*_ 3 # @author :yinzhengjie 4 # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 # EMAIL:y1053419035@qq.com 6 7 8 # user_dic = { 9 # ‘yinzhengjie‘:‘123‘, 10 # ‘Golang‘:"666", 11 # ‘Python‘:"888", 12 # } 13 # 14 # with open("user.db","w",encoding="utf-8")as f: 15 # f.write(str(user_dic)) 16 17 18 19 20 db_path = "user.db"2122 login_dic ={ 23‘user‘:None, 24"status":False, 25} 2627def auth(func): 28def wrapper(*args,**kwargs): 29if login_dic[‘user‘] and login_dic[‘status‘]: 30 res = func(*args, **kwargs) 31return res 32 username = input("username:") 33 password = input("password:") 34 with open(db_path, "r", encoding="utf-8")as f: 35 user_dic = eval(f.read()) 36if username in user_dic and password == user_dic[username]: 37print(‘login successful‘) 38 login_dic[‘user‘] = username 39 login_dic[‘status‘] = True 40 res = func(*args,**kwargs) 41return res 42else: 43print(‘login error‘) 44return wrapper 4546@auth 47def Index(): 48print("Welcome to Index!") 4950@auth 51def home(name): 52print("Welecome %s to home page!"%name) 5354Index() 55 home("尹正杰") 5657585960以上代码执行结果如下: 61username:yinzhengjie 62 password:123 63login successful 64Welcome to Index! 65 Welecome 尹正杰 to home page!
2.编写下载网页内容的函数,要求功能是:用户传入一个URL,函数返回下载页面的内容。
1 # !/usr/bin/env python 2 # _*_coding:utf-8_*_ 3 # @author :yinzhengjie 4 # blog:http://www.cnblogs.com/yinzhengjie/tag/python%E8%87%AA%E5%8A%A8%E5%8C%96%E8%BF%90%E7%BB%B4%E4%B9%8B%E8%B7%AF/ 5 # EMAIL:y1053419035@qq.com 6 7 8 from urllib.request import urlopen 9import os 1011 cache_path=r‘cache.txt‘12def make_cache(func): 13def wrapper(*args,**kwargs): 14if os.path.getsize(cache_path):#说明有缓存15print(‘\033[45m=========有缓存=========\033[0m‘) 16 with open(cache_path,‘rb‘) as f: 17 res=f.read() 1819else: 20 res=func(*args,**kwargs) #下载21 with open(cache_path,‘wb‘) as f: #制作缓存22 f.write(res) 2324return res 2526return wrapper 2728@make_cache 29def get(url): 30return urlopen(url).read() 313233print(‘============first============‘) 34print(get(‘http://www.cnblogs.com/yinzhengjie‘)) 35print(‘============second===========‘) 36print(get(‘http://www.cnblogs.com/yinzhengjie‘)) 37print(‘============third============‘) 38print(get(‘http://www.cnblogs.com/yinzhengjie‘))
原文:https://www.cnblogs.com/yinzhengjie/p/8467930.html
内容总结
以上是互联网集市为您收集整理的python中的无参装饰器和有参装饰器全部内容,希望文章能够帮你解决python中的无参装饰器和有参装饰器所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。