第三课、面向对象的应用(异常处理、文件备份)

一、课程介绍

  1.1 课程概要

  章节概要

  • 迭代器
  • 生成器
  • 实战:模拟range函数效果

二、装饰器的介绍与应用

  2.1 什么是装饰器

   装饰器

  • 用于拓展原来函数功能的一种函数
  • 返回函数的函数
  • 在不用更改原函数的代码前提下给函数增加新的功能

  如果没有装饰器

 1 def hello():
 2     """简单功能模拟"""
 3     print('hello world')
 4
 5
 6 def test():
 7     print('test..')
 8
 9
10 def hello_wrapper():
11     """新的函数,包裹原来的hello"""
12     print('开始执行hello')
13     hello()
14     print('结束执行')
15
16
17 def test_wrapper():
18     """新的函数,包裹原来的hello"""
19     print('开始执行hello')
20     test()
21     print('结束执行')
22
23
24 if __name__ == '__main__':
25     # hello()
26     hello_wrapper()

  实现装饰器

 1 def log(func):
 2     """记录函数执行的日志"""
 3     def wrapper():
 4         print('start...')
 5         func()
 6         print('end...')
 7     return wrapper
 8
 9
10 def log_in(func):
11     """记录函数执行的日志"""
12     def wrapper():
13         print('开始进入。。。')
14         func()
15         print('结束...')
16     return wrapper
17
18
19 @log
20 def hello():
21     # """简单功能模拟"""
22     print('hello world')
23
24
25 @log
26 @log_in
27 def test():
28     print('test..')
29
30
31 if __name__ == '__main__':
32     # hello()
33     test()
12-15 03:05
查看更多