第三课, 面向对象的应用 (异常处理, 文件备份)
一, 课程介绍
1.1 课程概要
章节概要
迭代器
生成器
实战: 模拟 range 函数效果
二, 装饰器的介绍与应用
2.1 什么是装饰器
装饰器
用于拓展原来函数功能的一种函数
返回函数的函数
在不用更改原函数的代码前提下给函数增加新的功能
如果没有装饰器
- def hello():
- """简单功能模拟"""
- print('hello world')
- def test():
- print('test..')
- def hello_wrapper():
- """新的函数, 包裹原来的 hello"""
- print('开始执行 hello')
- hello()
- print('结束执行')
- def test_wrapper():
- """新的函数, 包裹原来的 hello"""
- print('开始执行 hello')
- test()
- print('结束执行')
- if __name__ == '__main__':
- # hello()
- hello_wrapper()
实现装饰器
- def log(func):
- """记录函数执行的日志"""
- def wrapper():
- print('start...')
- func()
- print('end...')
- return wrapper
- def log_in(func):
- """记录函数执行的日志"""
- def wrapper():
- print('开始进入...')
- func()
- print('结束...')
- return wrapper
- @log
- def hello():
- # """简单功能模拟"""
- print('hello world')
- @log
- @log_in
- def test():
- print('test..')
- if __name__ == '__main__':
- # hello()
- test()
来源: http://www.bubuko.com/infodetail-3327776.html