Python with understanding
Tags (space separated): Python
with
As a kind 上下文管理器
, Python
the role in can be simply understood as try...except...finally
a processing flow used to replace .
with
__enter__
Initialize through the method, and then __exit__
do the aftermath and handle exceptions in it. It with
provides a very convenient expression for some tasks that need to be set in advance and cleaned up afterwards . After the following with
statement is evaluated, the __enter__
method that returns the object will be called , and __enter__
the returned result will be assigned to the as
following variable. When the with
following code blocks are all executed, the __exit__()
method that returns the object will be called to perform cleanup work.
Just like in file operations:
file = open("file.txt")
try:
data = file.read()
finally:
file.close()
After use with...as...
, the code will be reduced to:
with open("file.txt") as file:
data = file.read()
In the above code, the open()
function will return an file
object of type , which has an __enter__
and __exit__
method (you can dir(file),type(file)
view it), and then call the __enter__
method of the object to assign the return value to the file
variable, so there with...as...
is no need to close the display when using the operation file file.
Since we know with...as...
the most important thing is __enter
, __exit__
that we can customize a context manager.
among them:
__enter__
The method will be called before entering the code block.
__exit__
Will be called after leaving the code block (even if an exception is encountered in the code block).
class WithDemo:
def __enter__(self):
print "in __enter__"
return "WithDemo"
def __exit__(self, type, value, trace):
print "in __exit__"
def get_demo_with():
return WithDemo()
with get_demo_with() as demo:
print "demo:", demo
The execution result is:
in __enter__
demo:WithDemo
in __exit__
At the beginning, it was said that the process operation that with..as..
can be used instead try...except...finally...
, try...finally...
the situation mentioned above , what about abnormal? If you look carefully, you will find __exit__()
three parameters, and these three parameters are the parameters that provide handling for exceptions.
class WithDemo:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print "type:", type
print "value:", value
print "trace:", trace
def create_trace(self):
return (1/10) + 10
with WithDemo() as demo:
demo.create_trace()
Run the code and you will find that the code prints type, value, and trace.