The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 26 Python Implementation of Classes and Objects - Context Managers and the with Statement
This paper mainly introduces how to use context managers and the with statement to replace the try. .. finally statement in exception handling when using Python Object Oriented programming, and also presents the advantages and application scenarios of the with statement.
This document mainly introduces how to use Python for Object Oriented programming, and requires readers to have a basic understanding of Python syntax and microcontroller development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications, taking the common serial port data transmission and reception, data processing, dynamic graph drawing of host computer and slave computer as application examples, and uses Sourcetrail code software for visual code reading to facilitate readers' understanding.
The link to obtain the relevant sample code is as follows:
https://github.com/leezisheng/Python-OOP-Demo
Body Text
The with statement is a function related to exception handling introduced starting from Python 2.6. It is applicable to scenarios where resources are accessed, ensuring that necessary "cleanup" operations are performed to release resources regardless of whether an exception occurs during use, such as automatic file closure after use, and automatic acquisition and release of locks in threads.
The with statement is a new control flow structure, whose basic form is as follows:
with expression [as variable]:
with-block
expression is an expression that returns an object complying with the context management protocol, and this object must implement the following two methods:
enter (): Called when entering a with statement block, and returns an object for use by the as clause.
exit (exc_type, exc_value, traceback): is called when exiting a with statement block, and is used to perform cleanup operations.
In exception handling, the `with. ..` statement is equivalent to a shorthand for the `try-finally` statement and can replace its functionality. A typical example is file processing: you need to obtain a file handle, read data from the file, and then close the file handle. If you do not use the `with` statement, the code would be as follows:
file = open("foo.txt")
try:
data = file.read()
finally:
file.close()
Although this code works fine, it's overly verbose. This is exactly where the `with` statement comes into play. Apart from offering more elegant syntax, `with` can also properly handle exceptions arising from the context. Here is the version of the code using `with`:
with open("foo.txt") as file:
data = file.read()
In this example, open () function returns a file object that implements the context management protocol. The with statement automatically calls the __enter__() method of the file object to return the file object, and automatically calls the __exit__() method to close the file at the end of the statement block. This ensures that the file is properly closed after use, avoiding the problem of resource leakage.
The advantages of using the with statement include:
Conciseness and readability: Compared with manual resource management, with statements make the code more concise and easier to understand.
Exception Safety: Even if an exception occurs in the Code Block, resources can be properly released, thus avoiding resource leakage.
Reusability: Custom context managers can be created to encapsulate the logic for resource acquisition and release.