上下文(context)管理器
上下文管理器的协议:
enter进入方法
exit退出方法
import sys
class LookingGlass:
def __enter__(self):
# sys.stdout.write负责将文本输出到控制台,将sys.stdout.write的地址赋给self.original_write
self.original_write = sys.stdout.write
# 让输出变为反向输出
sys.stdout.write = self.reverse_write
return "AABBCC"
def reverse_write(self, text):
"""
负责将text反向输出
:param text:文本
:return:
"""
self.original_write(text[::-1])
def __exit__(self, exc_type, exc_val, exc_tb):
"""
:param exc_type: 异常的类型
:param exc_val: 异常实例 eg: except ZeroDivisionError as data
:param exc_tb: traceback对象
:return:
"""
sys.stdout.write = self.original_write # 恢复至正常输出
# 异常处理略过
return True # 如果返回True, 则代表已经正确处理异常,如果返回True以外的其他值,则代表异常未处理
测试代码
# 将文本反向输出
with LookingGlass() as what:
print("ABCDEFG")
print(what)
print("123456789")
输出如下
GFEDCBA
CCBBAA
123456789
可以看出,在with语句的上下文环境中,输出变为逆向输出,一旦离开上下文环境,输出恢复正常。what为enter方法的返回值。
简化上下文管理器
import contextlib
# 装饰器
@contextlib.contextmanager
def looking_glass():
import sys
original_write = sys.stdout.write
def reverse_write(text):
original_write(text[::-1])
sys.stdout.write = reverse_write
try:
yield 'aaabbbbccc' # enter的返回值
except Exception:
print("处理异常")
# 以异常处理为分界线,上边为enter的功能,下面是exit的功能,yield为enter的返回值
sys.stdout.write = original_write
with looking_glass() as what:
print("abcdefg")
print(what)
print("123456789")
gfedcba
cccbbbbaaa
123456789