with
在python开发中,尤其是文件操作中经常会碰到 with语法,常见格式如下:
with open(r'fisher.py','r') as f:
print(f.read())
1、首先要确定什么样的对象可以使用with语句?
实现了上下文协议的对象就可以使用with语句。对于实现了上下文协议的对象,我们通常称为上下文管理器。
2、一个上下文管理器如何实现上下文协议呢?
实现了__enter__和__exit__这两个方法就是实现了上下文协议。
3、示例:
class Sample():
def __init__(self):
self.enter = "Enter..."
self.exit = "Exit..."
def __enter__(self):
print(self.enter)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"exc_type: {exc_type}")
print(f"exc_val: {exc_val}")
print(f"exc_tb: {exc_tb}")
print(self.exit)
return True
def fun(self):
print("fun execute!!!")
with Sample() as s:
1/0
s.fun()
# 运行结果:
Enter...
exc_type: <class 'ZeroDivisionError'>
exc_val: division by zero
exc_tb: <traceback object at 0x000002DCF177EE48>
Exit...
(1) 例子中Sample() 类的实例实现了 __enter__和__exit__ 方法,所以它是上下文管理器。
(2) 可以看到 with 语句首先执行了类中 __enter__ 中的代码,再去执行 with 语句中的代码,最后去执行类中 __exit__ 中的代码。
(3) with 语句中 as 后面是 __enter__ 函数 return 的结果。
(4) __exit__ 函数必须有参数:exc_type, exc_val, exc_tb,一般 __exit__ 都是用来做资源回收,除了这个功能外它还能进行异常处理。
exc_type:异常类型;
exc_val:异常值;
exc_tb:tracback 对象。
(5) __exit__ 函数只能返回 True 或 False,当我们不指定返回值的时候默认返回 False。
return True:__exit__ 方法执行完后 with 外部将不会抛出异常。
return False:__exit__ 方法执行完后 with 外部将抛出异常。