程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python Tutorial: Usage of the with Statement

編輯:Python

One, the principle of with statement

Context Management Protocol: Contains the methods __enter__() and __exit__(), and objects that support this protocol must implement these two methods.

Context Manager: An object that supports the context management protocol. This object implements the methods __enter__() and __exit__().The context manager defines the runtime context to be established when executing the with statement, and is responsible for executing the entry and exit operations in the context of the with statement block.A context manager is usually invoked using the with statement, but can also be used by calling its methods directly.

After talking about the above two concepts, let's start with the common expressions of the with statement, a basic with expression whose structure is as follows:

with EXPR as VAR:BLOCK

where EXPR can be any expression; as VAR is optional.The general execution process is as follows:

  • Execute EXPR to generate context manager context_manager;
  • Get the __exit()__ method of the context manager and save it for later calls;
  • Call the __enter__() method of the context manager; if the as clause is used, assign the return value of the __enter__() method to the as clauseVAR;
  • Execute the expression in BLOCK;
  • Regardless of whether an exception occurs during execution, the __exit__() method of the context manager is executed, and the __exit__() method is responsible for performing "cleanup" work, such as releasingresources, etc.If no exception occurs during execution, or the statement break/continue/return is executed in the statement body, __exit__(None, None, None) is called with None as a parameter; if an exception occurs during execution,Then use the exception information obtained by sys.exc_info as the parameter to call __exit__(exc_type, exc_value, exc_traceback);
  • When an exception occurs, if __exit__(type, value, traceback) returns False, the exception will be re-thrown, and the statement logic other than with will handle the exception, which is also a common practice; ifIf True is returned, the exception is ignored and the exception is no longer handled.

Second, custom context manager

Python's with statement is an effective mechanism to make the code more concise, and at the same time, when an exception occurs, the cleanup work is easier.

class DBManager(object):def __init__(self):passdef __enter__(self):print('__enter__')return selfdef __exit__(self, exc_type, exc_val, exc_tb):print('__exit__')return Truedef getInstance():return DBManager()with getInstance() as dbManagerIns:print('with demo')

with must be followed by a context manager. If as is used, the return value of the context manager's __enter__() method is assigned to target, which can be a single variable, or byA tuple enclosed by "()" (cannot be a list of variables separated only by ",", must add "()")

The result of running the code is as follows:

'''__enter__with demo__exit__'''

Result analysis: When we use with, the __enter__ method is called, and the return value is assigned to the variable after as, and __exit__Method

'''Problems encountered during study and no one answered?Xiaobian created a Python learning exchange group: 711312441Looking for like-minded friends to help each other, there are also good video learning tutorials and PDF e-books in the group!'''class With_work(object):def __enter__(self):"""Called when entering the with statement"""print('enter called')return "xxt"def __exit__(self, exc_type, exc_val, exc_tb):"""Called by with when leaving with"""print('exit called')with With_work() as f:print(f)print('hello with')
'''enter calledxxthello withexit called'''

Three, Summary

Customize context managers to manage resources in the software system, such as database connections, access control of shared resources, etc.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved