Python编程之基础知识练习_002

练习内容:

 (1)函数装饰器。
 (2)使用魔术方法__call__,将一个类实现为装饰器
 (3)使用魔术方法__enter__与__exit__,实现一个类,使其能为函数提供上下文管理功能。

1.函数装饰器

 1 __author__ = 'Orcsir'
 2 from functools import wraps, update_wrapper
 3 import time
 4 
 5 
 6 # 将一个函数实现为装饰器
 7 def timeit(func):
 8     @wraps(func)
 9     def _wrapper(*args, **kwargs):
10         print("Inject some code before func run.")
11 
12         ret = func(*args, **kwargs)
13 
14         print("Inject some code after func run.")
15 
16         return ret
17 
18     return _wrapper
19 
20 
21 @timeit
22 def func(*args, **kwargs):
23     print("func start processing.")
24     time.sleep(2)  # 模拟处理时间
25     print("func end processing.")
26     return None
27 
28 # Test
29 func(1,2)

 2.使用魔术方法__call__,将一个类实现为装饰器

 1 __author__ = 'Orcsir'
 2 from functools import wraps, update_wrapper
 3 import time
 4 
 5 # 将一个类实现为装饰器
 6 class TimeIt:
 7     def __init__(self, wrapped):
 8         self.__wrapped = wrapped
 9         wraps(wrapped)(self)
10 
11     def __call__(self, *args, **kwargs):
12         print("Inject some code before func run.")
13         ret = self.__wrapped(*args, **kwargs)
14         print("Inject some code after func run.")
15         return ret
16 
17 
18 @TimeIt
19 def func(*args, **kwargs):
20     print("func start processing.")
21     time.sleep(2)  # 模拟处理时间
22     print("func end processing.")
23     return None
24 
25 # Test
26 func()

3.使用魔术方法__enter__与__exit__,实现一个类,使其能为函数提供上下文管理功能

 1 __author__ = 'Orcsir'
 2 from functools import wraps, update_wrapper
 3 import time
 4 
 5 # 实现一个类,使其为函数提供上下文管理功能
 6 class ContextMage4Func:
 7     def __init__(self, func):
 8         self.__func = func
 9 
10     def __enter__(self):
11         print("为func函数的运行准备环境.")
12         return self.__func
13 
14     def __exit__(self, exc_type, exc_val, exc_tb):
15         print("func函数退出或出现异常时,做一些清理工作.")
16 
17 
18 def func(*args, **kwargs):
19     print("func start processing.")
20     time.sleep(2)  # 模拟处理时间
21     print("func end processing.")
22     return None
23 
24 # Test
25 with ContextMage4Func(func):
26     func(1, 2)
27 print("~~~~~~~~~~~~~~~~~~~~~~")
28 with ContextMage4Func(func) as f:
29     f(1, 2)

猜你喜欢

转载自www.cnblogs.com/orcsir/p/9029328.html