__enter__ and __exit__

1. __enter__ and __exit__

We know that when manipulating file objects, we can write:

with is a factory function, and what open gets is a class, which is assigned the value f.

1 with open('a.txt') as f:
2 'Code Blocks'

The above is called the context management protocol, the with statement. In order for an object to be compatible with the with statement, the __enter__ and __exit__ methods must be declared in the object's class.

#Context management protocol 
class Open:
     def  __init__ (self,name):
        self.name=name

    def  __enter__ (self):
         print ( ' The with statement appears, the __enter__ of the object is triggered, and the return value is assigned to the variable declared as ' )
         return self 
    def  __exit__ (self, exc_type, exc_val, exc_tb):
         print ( ' When the code block in with is executed, execute me ' )

with Open( ' a.txt ' ) as f:       # Instead of returning the result of Open('a.txt') to f, it triggers the enter method in Open and returns the return value of the enter function to f
     print ( ' = ====>Execute code block ' )   
   print (f)  #<__main__.Foo object at 0x0000000001199198> #Explain that f is an object    
print (f.name) #You can use f to call the variable name in it #Wait for with corresponding The execution of the code block ends, triggering the exit function

The three parameters in __exit__() represent the exception type, the exception value and the traceback information respectively. If an exception occurs in the code block in the with statement, the code after the with cannot be executed.

  View Code

If the return value of __exit() is True, the exception will be cleared, as if nothing happened, and the statement after with executes normally

  View Code
  Exercise: Simulate Open

Use or benefit:

1. The purpose of using the with statement is to put the code block into the with for execution. After the with ends, the cleanup work is automatically completed without manual intervention.

2. In a programming environment that needs to manage some resources such as files, network connections and locks, you can customize the mechanism for automatically releasing resources in __exit__, you don't need to worry about this problem, it will be very useful

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324672409&siteId=291194637