<>1. Context manager

As long as a class is implemented __enter__() and __exit__() These two methods , Objects created through this class are called context managers .

The context manager can use the with sentence ,with What makes statements so powerful , It is supported by the context manager , That is to say, it was used just now open
The file object created by the function is a context manager object .

Custom context manager , Simulate file operation :

Define a File class , realization __enter__() and __exit__() method , Then use the with Statement to complete the operation file , Sample code :
# Custom context manager class class File(object): def __init__(self, file_name, file_mode): self
.file_name = file_name self.file_mode = file_mode def __enter__(self): #
The above method , Responsible for returning operation object resources , such as : File object , Database connection object self.file = open(self.file_name, self.file_mode)
return self.file def __exit__(self, exc_type, exc_val, exc_tb): #
The following method , Responsible for releasing object resources , such as : Close the file , Close database connection object self.file.close() print('over') # with sentence
Used with context manager objects with File('1.txt', 'r') as f: # content = f.read() # print(content)
f.write('qqq') # report errors , However, the close connection operation was still performed
Code description :

* __enter__ Means the above method , You need to return an operation file object
* __exit__ Means the following method ,with The statement is executed automatically when it is completed , The method is executed even if an exception occurs
<>2. Implementation of context manager decorator

If you want a function to be a context manager ,Python A @contextmanager The decorator of , It further simplifies the implementation of context manager . adopt
yield Divide the function into two parts ,yield The above statement is in the __enter__ Method ,yield The following statement is in the __exit__ Method , Follow closely
yield The following argument is the return value of the function .
from contextlib import contextmanager # Add the decorator , The object created by the following function is a context manager
@contextmanagerdef my_open(file_name, file_mode): global file try: file = open(
file_name, file_mode) # yield The code before the keyword can be considered as the above method , Responsible for returning operation object resources yield file except
Exceptionas e: print(e) finally: # yield The code after the keyword can be considered as the following method , The operation responsible for releasing resources file.close
() print('over') # Ordinary functions cannot be combined with Statement usage with my_open('1.txt', 'r') as file: #
content = file.read() # print(content) file.write('1')

Technology