说明
运行逻辑与 try…finally… 类似
构建
class 类名():
def __init__(self, name):
self._name = name
def __enter__(self):
// 运行 with 中代码前执行
return self._name // 返回值通过 as 接收
def __exit__(self, exc_type, exc_val, exc_tb):
// with 中代码运行结束后执行,包括因异常结束
// 若因异常结束,将异常信息以参数形式传入
使用
with 类名() as 参数[用于接收__enter__返回的值]:
代码
实例
class Test:
def __init__(self, name):
self._name = name
def __enter__(self):
print("开始")
return self._name
def __exit__(self, exc_type, exc_val, exc_tb):
print(exc_type)
print(exc_val)
print(exc_tb)
print("结束")
if __name__ == '__main__':
with Test("joshua") as name:
print("name", name)
1 / 0
运行结果
开始
name joshua
<class 'ZeroDivisionError'>
division by zero
<traceback object at 0x7f53b848e730>
结束
Traceback (most recent call last):
File "-----", line 23, in <module>
1 / 0
ZeroDivisionError: division by zero