__exit__ 在Python中
上下文管理器用于管理程序使用的资源。使用完成后,我们要释放内存并终止文件之间的连接。如果不释放它们,则会导致资源泄漏,并可能导致系统变慢或崩溃。即使我们不释放资源,上下文管理器也会隐式执行此任务。
Refer the below article to get the idea about basics of Context Manager.
__exit__() 方法
这是ContextManager
类的一个方法。 __exit__
方法负责释放当前代码片段占用的资源。在我们处理完资源之后,无论如何都必须执行此方法。此方法包含正确关闭资源处理程序的指令,以便释放资源以供操作系统中的其他程序进一步使用。
如果引发异常;它的类型、值和回溯作为参数传递给__exit__()
。否则,将提供三个None
参数。如果异常被抑制,则__exit__()
方法的返回值将为True
,否则为False
。
syntax: __exit__(self, exception_type, exception_value, exception_traceback)
parameters:
exception_type: indicates class of exception.
exception_value: indicates type of exception . like divide_by_zero error, floating_point_error, which are types of arithmetic exception.
exception_traceback: traceback is a report which has all of the information needed to solve the exception.
# 示例 1: .
# Python program creating a
# context manager
class ContextManager():
def __init__(self):
print('init method called')
def __enter__(self):
print('enter method called')
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exit method called')
with ContextManager() as manager:
print('with statement block')
输出 :
init method called
enter method called
with statement block
exit method called
# 示例 2:了解__exit__()
的参数。我们将创建一个上下文管理器,用于划分两个数字。如果
# Python program to demonstrate
# __exit__ method
class Divide:
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def __enter__(self):
print("Inside __enter__")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("\nInside __exit__")
print("\nExecution type:", exc_type)
print("\nExecution value:", exc_value)
print("\nTraceback:", traceback)
def divide_by_zero(self):
# causes ZeroDivisionError exception
print(self.num1 / self.num2)
# Driver's code
with Divide(3, 1) as r:
r.divide_by_zero()
print("................................................")
# will raise a ZeroDivisionError
with Divide(3, 0) as r:
r.divide_by_zero()
输出:
Inside __enter__
3.0
Inside __exit__
Execution type: None
Execution value: None
Traceback: None
................................................
Inside __enter__
Inside __exit__
Execution type:
Execution value: division by zero
Traceback:
Traceback (most recent call last):
File "gfg.py", line 32, in
r.divide_by_zero()
File "gfg.py", line 21, in divide_by_zero
print(self.num1 / self.num2)
ZeroDivisionError: division by zero