First, the concept
Context Manager: the object is to achieve a context management protocol. Mainly used to save and restore all kinds of global state, close the file and so on. Context Manager itself is a decorator.
Context allows to automatically start and end, and a number of things. For example, when use with ... as opening a file, python automatically creates a context manager.
Second, the context management protocol
Context Management protocol comprises two methods:
contextmanager .__ enter __ (): the former with statement block of code, performs The __enter __ (), the returned value is assigned to the variable with the sentence as.
contextmanager .__ exit __ (): block of code with statement ends or an error, performs __exit __ ().
Third, with ... as an example instead of try ... except ... finally open the file
# Error writing
the try :
f = Open ( " xxx " )
do something
the except :
do something
a finally :
f.close
# #################
# correct wording
'' ' write finally, because to prevent the program can not be thrown finally close the file,
but need to close the file has a premise that the file has been opened. In the first paragraph of the error code,
if an exception occurs when f = open ( 'xxx'), such as the file does not exist,
immediately you can know the execution f.close () is meaningless, after the correct solution is the first Sec Code '' '
the try :
F = Open ( " XXX")
the except :
Print ( " Fail to Open " )
exit(-1)
try:
do something
except:
do something
finally:
f.close()
with...as...:
# Open a file and ensure that it finally closed
with Open ( " xxx " ) AS f:
the Data = f.read ()
do something with the Data
# to open multiple
with Open ( " xxx " ) AS f1, Open ( " yyy " ) F2 AS:
do something with f1, F2
Fourth, the custom context manager
class MyContextManager(object):
def __init__(self):
print("init 函数被调用")
def __enter__(self):
print("enter函数被调用,返回一个对象")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit 函数被调用")
with MyContextManager():
print("创建实例做点什么")
################
#结果:
init 函数被调用
enter函数被调用,返回一个对象
创建实例做点什么
exit 函数被调用