當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。