当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python __exit__用法及代码示例


上下文管理器用于管理程序使用的资源。使用完成后,我们必须释放内存并终止文件之间的连接。如果不释放它们,则将导致资源泄漏,并可能导致系统变慢或崩溃。即使我们不释放资源,上下文管理器也会隐式执行此任务。

Refer the below article to get the idea about basics of Context Manager.

  • Context Manager
  • __exit__()方法

    这是一种方法ContextManager类。的__exit__ 方法负责释放当前代码段占用的资源。无论我们在处理完资源后如何执行此方法,都必须执行。此方法包含正确关闭资源处理程序的指令,以便释放资源以供OS中的其他程序进一步使用。

    如果引发异常;其类型,值和追溯作为参数传递给__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
    
    





    注:本文由纯净天空筛选整理自shaikameena大神的英文原创作品 __exit__ in Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。