With statement:
Afterwards do clean up work. such as file processing, need to get a file handle, read the data from the file, and then close the file handle
Without the With statement, the code is as follows:
File = open ("/tmp/foo.txt"= file.read () file.close ()
Here are two questions. One is to forget to close the file handle, and the other is the file read data exception, no processing. The following is an enhanced version of handling exceptions:
File = open ("/tmp/foo.txt")try: = file.read () finally : file.close ()
This code works fine, but it's too verbose.
With can handle exceptions generated by the context, the code is as follows:
With open ("/tmp/foo.txt") as file: = File.read ()
With how it works:
The basic idea is that the object with which the value is evaluated must have a __enter__ () method, a __exit () __ method.
Immediately after the statement that follows with is evaluated, the __enter__ () method of the returned object is called, and the return value of the method is assigned to the variable following the AS. The __exit () __ method of the previous return object is called when all the code blocks behind with are executed.
classSample:def __enter__(self):Print("In __enter__ ()") return "Foo" def __exit__(self, type, value, trace):Print("In __exit__ ()")defget_sample ():returnSample () with Get_sample () as Sample:Print("Sample:", sample)
As you can see:
The 1.__enter__ () method is executed
The value returned by the 2.__enter__ () method is "Foo" in---example, assigned to the variable "sample"
3. Execute code block, print variable "sample" with the value "Foo"
The 4.__exit__ () method is called
With the real power of it is that it can handle exceptions. Perhaps you have noticed that the __exit__ method of the sample class has three parameters Val, type, trace. These parameters are useful in handling exceptions. Change the code below to see how it works.
class Sample: def __enter__ (self): return Self def __exit__ (self, type, value, trace): Print ("type")
Python with as usage