Python advanced (28)—with statement

Original link: https://chegva.com/5473.html

◎Knowledge points

  1. The use of the with statement and exception handling

  2. with statement execution flow

◎Script practice

 """with statement"""  """ If a class object implements the special methods __enter__() and __exit__(), then the class object is said to comply with the context management protocol, Also, an instance object of this class object is called a context manager. The with statement will cause the context manager to create a runtime context and automatically call the special method __enter__() when entering the runtime context, The special method __exit__() is automatically called when leaving the runtime context. The syntax of the with statement: with context expression [as variable]: with statement body  If an exception occurs in the body of the with statement, the three elements in the return value of sys.exc_info() will be automatically passed to the formal parameters exc_type, exc_val, and exc_tb of the special method __exit__(). The type of exception, the error message of the exception, and the trace information of the exception call stack are similar to the finally clause. The special method __exit__() is always called, and resources are usually released in the special method __exit__(). For example: close file, close network connection, etc."""  class MyContextManager(object): def __enter__(self): print("The special method __enter__() is called") return self  def __exit__(self, exc_type, exc_val, exc_tb): print("The special method __exit__() was called")  print("Exception type: %s" % exc_type) print("Exception error message: %s" % exc_val) print("Exception call stack trace: %s" % exc_tb)  # return True  def do_sth(self): print("The method do_sth() is called") print(1 / 0)  """ with MyContextManager() as mcm: mcm.do_sth() """  """ When an exception occurs in the body of the with statement and the special method __exit__() does not return True, in order to allow the program to continue executing, The thrown exception instance object can be caught and handled using the try-except statement. """  try: with MyContextManager() as mcm: mcm.do_sth() except ZeroDivisionError as err: print(err) 

with语句的执行流程.png

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/with.py

This article is reprinted from: https://chegva.com/5473.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment