7-3 How to make objects support context management

Wtih XXX  as yy:

 

Here, yy is the value returned by enter

 

Define the __enter__ method in the class

def __enter__(self):

....

return self

 

#A total of 4 parameters, the last 3 are related to exceptions, they are exception type, exception value, traced stack

def __exit__(self,exc_type,exc_val,exc_tb):

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325940749&siteId=291194637