This syntax is used instead of the traditional try...finally syntax.
Copy CodeThe code is as follows:
With EXPRESSION [as VARIABLE] With-block
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 code blocks following the with are executed.
Copy the Code code as follows:
File = Open ("/tmp/foo.txt")
Try
data = File.read ()
Finally
File.close ()
Use with...as ... Replace the modified code with the following:
Copy CodeThe code is as follows:
With open ("/tmp/foo.txt") as File:
data = File.read ()
#!/usr/bin/env python
# with_example01.py
Class Sample:
def __enter__ (self):
Print "in __enter__ ()"
Return "Foo"
def __exit__ (self, type, value, trace):
Print "in __exit__ ()"
Def get_sample ():
Return Sample ()
With Get_sample () as Sample:
Print "Sample:", sample
Execution results are
Copy CodeThe code is as follows:
In __enter__ ()
Sample:foo
In __exit__ ()
1. The __enter__ () method is executed
2. The value returned by the __enter__ () method-This example is "Foo", assigned to the variable ' sample '
3. Execute code block, print variable "sample" with the value "Foo"
4. The __exit__ () method is called with the real power that it can handle exceptions. You may have noticed that the __exit__ method of the sample class has three parameters-Val, type, and trace. These parameters are quite useful in exception handling. Let's change the code to see how it works.