自学Python4.5-装饰器举例
2019-03-21 22:10
204 查看
自学Python之路-Python基础+模块+面向对象
自学Python之路-Python网络编程
自学Python之路-Python并发编程+数据库+前端
自学Python之路-django
自学Python4.5 - 装饰器举例
举例1. 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件)
要求登录成功一次,后续的函数都无需再输入用户名和密码
FLAG = False def login(func): def inner(*args,**kwargs): global FLAG '''登录程序''' if FLAG: ret = func(*args, **kwargs) # func是被装饰的函数 return ret else: username = input('username : ') password = input('password : ') if username == 'carlos' and password == 'carlos88': FLAG = True ret = func(*args,**kwargs) #func是被装饰的函数 return ret else: print('登录失败') return inner @login def shoplist_add(): print('增加一件物品') @login def shoplist_del(): print('删除一件物品') shoplist_add() shoplist_del()
举例2. 编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件
def log(func): def inner(*args,**kwargs): with open('log','a',encoding='utf-8') as f: f.write(func.__name__+'\n') ret = func(*args,**kwargs) return ret return inner @log def shoplist_add(): print('增加一件物品') @log def shoplist_del(): print('删除一件物品') shoplist_add() shoplist_del() shoplist_del() shoplist_del() shoplist_del() shoplist_del()
3. 编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
为题目1编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
import os from urllib.request import urlopen def cache(func): def inner(*args,**kwargs): if os.path.getsize('web_cache'): with open('web_cache','rb') as f: return f.read() ret = func(*args,**kwargs) #get() with open('web_cache','wb') as f: f.write(b'*********'+ret) return ret return inner @cache def get(url): code = urlopen(url).read() return code # {'网址':"文件名"} ret = get('http://www.baidu.com') print(ret) ret = get('http://www.baidu.com') print(ret) ret = get('http://www.baidu.com') print(ret)
相关文章推荐
- Python自学之路——自定义简单装饰器
- Python基础自学(第五章-函数进阶、迭代器和生成器、装饰器、上下文管理器、变量的作用域)
- 自学Python4.4-装饰器的进阶
- Python 装饰器举例
- 自学python(08),python种的装饰器
- python自学笔记(6)--Python函数式编程、函数的装饰器、递归
- 个人随手自学笔记--python3入门及基础知识点(5)—— 枚举、闭包、表达式、函数、装饰器、小爬虫
- 简单地理解 Python 的装饰器
- 自学Python day5--------函数式编程(返回函数)
- python 定时执行装饰器代码
- DayDayUP_Python自学教程[14]_python操作excel
- python_装饰器_语法糖
- 六、PYTHON 学习之装饰器使用
- Python的装饰器模式与面向切面编程详解
- 大专生自学Python到找到工作的经历
- 详解Python 装饰器执行顺序迷思
- Python装饰器原理
- python函数(二)详解高阶函数、函数闭包、装饰器、递归函数和生成器
- Python自学笔记之高级特性1——切片和迭代
- python学习: Python的装饰器