Labs / Python OOP

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

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents
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

Abstract:

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.

FreakStudio's Blog

You who study embedded systems still don't know Object Oriented? ?!

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 00 Introduction to Object Oriented Design Methodology

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 01 Basic Concepts of Object Oriented Programming

The Most Beginner-Friendly Object Oriented Programming Tutorial Online: 02 Python Implementation of Classes and Objects - Creating Classes with Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 03 Python Implementation of Classes and Objects – Adding Attributes to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 04 Python Implementation of Classes and Objects – Adding Methods to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 06 Python Implementation of Classes and Objects - Data Encapsulation of Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 07 Python Implementation of Classes and Objects - Type Annotations

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 08 Python Implementation of Classes and Objects - @property Decorator

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 09 Python Implementation of Classes and Objects - Relationships Between Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 10 Python Implementation of Classes and Objects - Class Inheritance and Liskov Substitution Principle

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 11 Python Implementation of Classes and Objects - Subclass Calling Parent Class Methods

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 12 Python Implementation of Classes and Objects - Using Python's logging Module to Output Program Runtime Logs

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 13 Python Implementation of Classes and Objects – Installation and Usage of Sourcetrail, a Fantastic Tool for Visual Code Reading

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 14 Python Implementation of Classes and Objects - Static Methods and Class Methods of Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 15 Python Implementation of Classes and Objects - The __slots__ Magic Method

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 16 Python Implementation of Classes and Objects - Polymorphism, Method Overriding and Open Closed Principle

The most beginner-friendly Object Oriented programming tutorial across the entire network: 17 Python implementation of classes and objects - duck typing and "file-like object"

The most beginner-friendly Object Oriented programming tutorial across the entire network: 18 Python implementation of classes and objects - multiple inheritance and serial port data curve plotting with PyQtGraph

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 19 Python Implementation of Classes and Objects – Using PyCharm to Automatically Generate File Comments and function Comments

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 20. Python Implementation of Classes and Objects – Implementation of Composition Relationship and CSV File Saving

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 21 Python Implementation of Classes and Objects - Multi-File Organization: Module and Package

The Best Entry-Level Object Oriented Programming Tutorial on the Whole Network: 22 Python Implementation of Classes and Objects - Exceptions and Syntax Errors

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 24 Python Implementation of Classes and Objects - Exception Catching and Handling

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines Input Data Types

More exciting content is available here:

Speed Up Your Python: A Quick Guide to Python Parallel Computing

Mastering the Debugging Principles of CM3 Microcontrollers in One Article

After half a month of dedicated grinding, the ultimate summary of embedded technology stack is now released

The "Secret Martial Arts Manual" for Computer Science Competitions

Document and Code Acquisition:

You can download the document via the following link:

https://github.com/leezisheng/Doc

19

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:

  1. enter (): Called when entering a with statement block, and returns an object for use by the as clause.
  2. 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:

  1. Conciseness and readability: Compared with manual resource management, with statements make the code more concise and easier to understand.
  2. Exception Safety: Even if an exception occurs in the Code Block, resources can be properly released, thus avoiding resource leakage.
  3. Reusability: Custom context managers can be created to encapsulate the logic for resource acquisition and release.
347622978