The use of with in python-a very useful feature
One, try, except, finally use
def exe_try():
try:
print("code started")
raise KeyError #抛出异常
return
except KeyError as e: #捕获异常
print("key error")
return 2
else:
print("other error")
return 3
finally: # 最后都会运行
print("finally")
return 4
if __name__ = "__main__":
result = exe_try()
print(result)
# code start
# key error
# finally
# 4
raise
Up key error
, then enter key error
exception handling, output is supposed to be 2, why last return
it was finally
4?
Because if finally
there are return
statements in the statement, 4 will definitely be output at the end, which can be thought of as a form of stack, and it key error
will return 2 after it is entered , but after 2 is put on the stack, the finally
statement will return 4, so the top element of the stack is output 4 first.
If you comment out the finally
statement return
, the result is 2.
Two, with statement
with context management protocol: __enter__
, __exit__
two magic function
class Sample:
def __enter__(self):
print("enter")
return self
def __exit__(self,exc_type,exc_value,exc_tb):
print("exit")
def do_something(self):
print("do somethong")
with Sample() as sample:
sample.do_something()
# enter
# doing something
# exit
It can be seen from the running result that it is called first __enter__
, then do_something
, and finally with
after leaving the statement, it will be called by default __exit__
.
With this context management protocol, we can define a class, and then use it with a with
statement, and can __enter__
acquire resources in __exit__
and release resources in it.
Three, subsection
For a more concise way to define a context manager, please see this blog